package com.younike.hlpay.util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class DesUtils {

    public static final String ENCODE = "UTF-8";

    private DesUtils() {
    }

    public static String encode(String key, String data) throws NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        try {
            byte[] keyByte = key.getBytes(ENCODE);
            byte[] dataByte = data.getBytes(ENCODE);
            byte[] valueByte = des3Encryption(
                    keyByte, dataByte);
            String value = new String(Base64.encodeBase64(valueByte), ENCODE);
            return value;
        } catch (Exception e) {
            System.err.println("3des加密失败:" + e.getMessage());
            throw e;
        }
    }

    public static String decode(String key, String value) throws NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        try {
            byte[] keyByte = key.getBytes(ENCODE);
            byte[] bytes = value.getBytes(ENCODE);
            byte[] dataByte = des3Decryption(keyByte,
                    Base64.decode(bytes));
            String data = new String(dataByte, ENCODE);
            return data;
        } catch (Exception e) {
            System.err.println("3des解密失败:" + e.getMessage());
            throw e;
        }
    }

    private static byte[] des3Encryption(byte[] key, byte[] data) throws
            NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException, IllegalStateException {
        final String Algorithm = "DESede";
        SecretKey deskey = new SecretKeySpec(key, Algorithm);
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        return c1.doFinal(data);
    }

    private static byte[] des3Decryption(byte[] key, byte[] data) throws
            NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException, IllegalStateException {
        final String Algorithm = "DESede";
        SecretKey deskey = new SecretKeySpec(key, Algorithm);
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.DECRYPT_MODE, deskey);
        return c1.doFinal(data);
    }
}
