提交 | 用户 | age
|
41d89b
|
1 |
package com.hx.util.mysql.aes; |
C |
2 |
|
|
3 |
import com.hx.util.StringUtils; |
|
4 |
import org.apache.commons.codec.binary.Hex; |
|
5 |
|
|
6 |
import javax.crypto.Cipher; |
|
7 |
import javax.crypto.spec.SecretKeySpec; |
|
8 |
import java.io.UnsupportedEncodingException; |
|
9 |
|
|
10 |
/** |
|
11 |
* mybatis数据库的AES_ENCRYPT(加密)和AES_DECRYPT(解密) |
|
12 |
* mybatis数据库的HEX(加壳)UNHEX(解壳) |
|
13 |
* @author CJH |
|
14 |
* @Date 2021-01-06 |
|
15 |
*/ |
|
16 |
public class MysqlHexAes { |
|
17 |
|
|
18 |
|
|
19 |
public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) { |
|
20 |
try { |
|
21 |
final byte[] finalKey = new byte[16]; |
|
22 |
int i = 0; |
|
23 |
for(byte b : key.getBytes(encoding)) { |
|
24 |
finalKey[i++%16] ^= b; |
|
25 |
} |
|
26 |
return new SecretKeySpec(finalKey, "AES"); |
|
27 |
} catch(UnsupportedEncodingException e) { |
|
28 |
throw new RuntimeException(e); |
|
29 |
} |
|
30 |
} |
|
31 |
|
|
32 |
/**AES 解密 |
|
33 |
* @param data 需要解密的数据 |
|
34 |
* @param aesKey 秘钥 |
|
35 |
* @param encoding 编码,不填默认UTF-8 |
e5bae5
|
36 |
* @return 解密数据 |
41d89b
|
37 |
*/ |
e5bae5
|
38 |
public static String decryptData(String data,String aesKey,String encoding) { |
C |
39 |
try{ |
|
40 |
if(StringUtils.isEmpty(encoding)){ |
|
41 |
encoding = "UTF-8"; |
|
42 |
} |
|
43 |
// Decrypt |
|
44 |
final Cipher decryptCipher = Cipher.getInstance("AES"); |
|
45 |
decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(aesKey, encoding)); |
|
46 |
data = new String(decryptCipher.doFinal(Hex.decodeHex(data.toCharArray()))); |
|
47 |
}catch (Exception e){ |
be7219
|
48 |
throw new RuntimeException("解密失败:"+e.getMessage()); |
41d89b
|
49 |
} |
e5bae5
|
50 |
return data; |
41d89b
|
51 |
} |
C |
52 |
|
|
53 |
/**AES加密 |
|
54 |
* @param data 需要解密的数据 |
|
55 |
* @param aesKey 秘钥 |
|
56 |
* @param encoding 编码,不填默认UTF-8 |
45549c
|
57 |
* @return 返回大写加密的数据 |
41d89b
|
58 |
*/ |
e5bae5
|
59 |
public static String encryptData(String data,String aesKey,String encoding) { |
C |
60 |
try { |
|
61 |
if (StringUtils.isEmpty(encoding)) { |
|
62 |
encoding = "UTF-8"; |
|
63 |
} |
|
64 |
// Encrypt |
|
65 |
final Cipher encryptCipher = Cipher.getInstance("AES"); |
|
66 |
encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(aesKey, encoding)); |
|
67 |
char[] code = Hex.encodeHex(encryptCipher.doFinal(data.getBytes(encoding))); |
|
68 |
StringBuilder builder = new StringBuilder(); |
|
69 |
for (char d : code) { |
|
70 |
builder.append(d); |
|
71 |
} |
|
72 |
data = builder.toString().toUpperCase(); |
|
73 |
} catch (Exception e) { |
be7219
|
74 |
throw new RuntimeException("加密失败:"+e.getMessage()); |
41d89b
|
75 |
} |
e5bae5
|
76 |
return data; |
41d89b
|
77 |
} |
C |
78 |
|
|
79 |
} |