AESUtils.java
1.94 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
package com.huaheng.common.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import org.apache.commons.codec.binary.Base64;
/**
* @author chenao
* @date 2022年02月25日 17:03
*/
public class AESUtils {
private final static String sKey="uUXsN6okXYqsh0BB";
public static String encrypt(String sSrc, String sKey) {
if (sKey == null) {
throw new IllegalArgumentException("sSrc不能为空");
}
// 判断Key是否为16位
if (sKey.length() != 16) {
throw new IllegalArgumentException("sKey长度需要为16位");
}
try {
byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//"算法/模式/补码方式"
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
//此处使用BASE64做转码功能,同时能起到2次加密的作用。
return new Base64().encodeToString(encrypted);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String decrypt(String sSrc) {
try {
byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//先用base64解密
byte[] encrypted1 = new Base64().decode(sSrc);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, StandardCharsets.UTF_8);
return originalString;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}