-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathaes-cbc-pkcs7.base64.java
81 lines (72 loc) · 3.05 KB
/
aes-cbc-pkcs7.base64.java
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
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
// java版aes-cbc-pkcs7加密解密base64输入输出
public class MyClass {
public static void main(String args[]){
String data = "this is Aes encryption with pkcs7";//加密的内容
String key = "1111111111111111"; //16位字符串密钥
String iv = "2222222222222222";//16位字符串偏移
//加密数据
String encodeResult = encryptAES(data,key,iv);
System.out.println(String.format("aes-cbc-128加密结果 -> %s",encodeResult));
//解密数据
String decodeResult = decryptAES(encodeResult,key,iv);
System.out.println(String.format("解密结果: -> %s",decodeResult));
}
/**
* 加密数据
* @param data 明文内容
* @param key 密钥
* @param iv 偏移
* @return
*/
private static String encryptAES(String data,String key,String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"), new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)));
byte[] result = cipher.doFinal(pkcs7padding(data, cipher.getBlockSize())); // 好气啊, 要自己手动实现 PKCS7Padding 填充
return Base64.getEncoder().encodeToString(result);
} catch (Exception e) {
e.printStackTrace();
}
return "NULL";
}
/**
* 解密数据
* @param data 加密内容
* @param key 密钥
* @param iv 偏移
* @return
*/
private static String decryptAES(String data, String key,String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"), new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)));
byte[] result = cipher.doFinal(Base64.getDecoder().decode(data));
return new String(result, StandardCharsets.UTF_8).trim();
} catch (Exception e) {
e.printStackTrace();
}
return "NULL";
}
/**
* pkcs7填充
* @param content
* @param blockSize
* @return
*/
private static byte[] pkcs7padding(String content, int blockSize) {
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
int pad = blockSize - (contentBytes.length % blockSize); // 计算需要补位的长度
byte padChr = (byte) pad; // 补位字符 (即用补位长度)
byte[] paddedBytes = new byte[contentBytes.length + pad]; // 在原有的长度上加上补位长度
System.arraycopy(contentBytes, 0, paddedBytes, 0, contentBytes.length); // 原有的先复制过去
for (int i = contentBytes.length; i < paddedBytes.length; i++) { // 补位字符填充
paddedBytes[i] = padChr;
}
return paddedBytes;
}
}