chenjiahe
2022-01-07 45549c4aee8a48c752f5036311da660535bfa722
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.hx.util.mysql.aes;
 
import com.hx.util.StringUtils;
import org.apache.commons.codec.binary.Hex;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
 
/**
 * mybatis数据库的AES_ENCRYPT(加密)和AES_DECRYPT(解密)
 * mybatis数据库的HEX(加壳)UNHEX(解壳)
 * @author CJH
 * @Date 2021-01-06
 */
public class MysqlHexAes {
 
 
    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 解密
     * @param data 需要解密的数据
     * @param aesKey 秘钥
     * @param encoding 编码,不填默认UTF-8
     * @return
     * @throws Exception
     */
    public static String decrpt(String data,String aesKey,String encoding)  throws Exception {
        if(StringUtils.isEmpty(encoding)){
            encoding = "UTF-8";
        }
        // Decrypt
        final Cipher decryptCipher = Cipher.getInstance("AES");
        decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(aesKey, encoding));
        return new String(decryptCipher.doFinal(Hex.decodeHex(data.toCharArray())));
    }
 
    /**AES加密
     * @param data 需要解密的数据
     * @param aesKey 秘钥
     * @param encoding 编码,不填默认UTF-8
     * @return 返回大写加密的数据
     * @throws Exception
     */
    public static String encrpt(String data,String aesKey,String encoding)  throws Exception {
        if(StringUtils.isEmpty(encoding)){
            encoding = "UTF-8";
        }
        // Encrypt
        final Cipher encryptCipher = Cipher.getInstance("AES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(aesKey, encoding));
        char[] code = Hex.encodeHex(encryptCipher.doFinal(data.getBytes(encoding)));
        StringBuilder builder = new StringBuilder();
        for (char d : code) {
            builder.append(d);
        }
        String strning = builder.toString();
        return strning.toUpperCase();
 
    }
 
}