AESBase64Utils.java
2.68 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.example.mypulsar.mq;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.pulsar.shade.org.apache.commons.codec.binary.Base64;
import org.apache.pulsar.shade.org.apache.commons.codec.binary.StringUtils;
public class AESBase64Utils {
private static final String AES = "AES";
// 加密算法
private String ALGO;
// 16位的加密密钥
private byte[] keyValue;
/**
* 用来进行加密的操作
*
* @param data
* @return
* @throws Exception
*/
public String encrypt(String data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(StringUtils.getBytesUtf8(data));
String encryptedValue = Base64.encodeBase64String(encVal);
return encryptedValue;
}
/**
* 用来进行解密的操作
*
* @param encryptedData
* @return
* @throws Exception
*/
public String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decodedValue = Base64.decodeBase64(encryptedData);
byte[] decValue = c.doFinal(decodedValue);
String decryptedValue = StringUtils.newStringUtf8(decValue);
return decryptedValue;
}
/**
* 根据密钥和算法生成Key
*
* @return
* @throws Exception
*/
private Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
public String getALGO() {
return ALGO;
}
public void setALGO(String aLGO) {
ALGO = aLGO;
}
public byte[] getKeyValue() {
return keyValue;
}
public void setKeyValue(byte[] keyValue) {
this.keyValue = keyValue;
}
public static String decrypt(String data, String secretKey) throws Exception {
// 创建加解密
AESBase64Utils aes = new AESBase64Utils();
// 设置加解密算法
aes.setALGO(AES);
// 设置加解密密钥
aes.setKeyValue(secretKey.getBytes());
// 进行解密后的字符串
return aes.decrypt(data);
}
public static String encrypt(String data, String secretKey) throws Exception {
// 创建加解密
AESBase64Utils aes = new AESBase64Utils();
// 设置加解密算法
aes.setALGO(AES);
// 设置加解密密钥
aes.setKeyValue(secretKey.getBytes());
// 进行解密后的字符串
return aes.encrypt(data);
}
}