AESUtis.java
1.75 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
package com.lhcredit.common.utils.oss;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;
public class AESUtis {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue ="Lhzx1234Lhzx1234".getBytes();
public static String encrypt(String valueToEnc) {
try{
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = c.doFinal(valueToEnc.getBytes(StandardCharsets.UTF_8));
// 可选地,对加密后的字节进行Base64编码以便于文本显示和传输
String encryptedValue = Base64.getEncoder().encodeToString(encValue);
return encryptedValue;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static String decrypt(String encryptedValue) {
try{
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
// 先将Base64编码的字符串解码回字节数组
byte[] decordedValue = Base64.getDecoder().decode(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue, StandardCharsets.UTF_8);
return decryptedValue;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
private static Key generateKey() {
try{
Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
}catch (Exception e){
}
return null;
}
}