package com.zcloud.common.utils;

import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
/**通常mysql中AES加密，和java中不⼀致，
 * 也就是说mysql中AES加密的东西，copy出来，
 * ⽤java代码不能解密
 * 下⾯⼤佬就来秀⼀波操作
 * */
public class AesEncryptor {

    private static String AESCODE  = "UTF-8";

    public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) {
        try {
            final byte[] finalKey = new byte[16];
            int i = 0;
            for(byte b : key.getBytes(encoding))
                finalKey[i++%16] ^= b;
            return new SecretKeySpec(finalKey, "AES");
        } catch(UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    /**AES 解密
     * data : 待解密的数据
     * */
    public static String decrpt(String AESKEY, String data)  throws Exception {
// Decrypt
        final Cipher decryptCipher = Cipher.getInstance("AES");
        decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(AESKEY, AESCODE));
        return new String(decryptCipher.doFinal(Hex.decodeHex(data.toCharArray())));
    }
    /**AES加密
     * AESKEY: KEY
     * data : 待加密的数据
     * */
    public static String encrpt(String AESKEY,String data)  throws Exception {
// Encrypt
        final Cipher encryptCipher = Cipher.getInstance("AES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(AESKEY, AESCODE));
        char[] code=  Hex.encodeHex(encryptCipher.doFinal(data.getBytes(AESCODE)));
        StringBuilder builder = new StringBuilder();
        for(char d:code) {
            builder.append(d);
        }
        String strning = builder.toString();
        return strning;
    }
    public static void main(String... args) throws Exception {
        System.out.println(encrpt("13133333333","113485")); //加密

        System.out.println(decrpt("13133333333","a6e6937a44ce951209adb197963fb418ed6145918cf3df80ca040ed26f8829ae"));
    }
}
