AES加解密(JAVA)

加解密JAVA 实现

引入依赖

1
2
3
4
5
6
7
8

<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
</dependencies>

代码

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
105
106
107
108
109
110
111
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Optional;
import java.util.UUID;

public class SecretUtil {
private static final Logger log = LoggerFactory.getLogger(SecretUtil.class);
private static final String AES = "AES";

private SecretUtil() {
}

/**
* 生成 key
* 返回到前端时:keyStr=Base64.getEncoder().encodeToString(key);
* 解密时:keyStr.getBytes()
*
* @return 密钥(Base64)
*/
public static String generateAesKey() {
return generateAesKey(null);
}

/**
* 生成 key
* 返回到前端时:keyStr=Base64.getEncoder().encodeToString(key);
* 解密时:keyStr.getBytes()
*
* @param word 辅助关键字
* @return key
*/
public static String generateAesKey(String word) {
/*随机UUID*/
try {
// 创建AES的 Key生产者
KeyGenerator gen = KeyGenerator.getInstance(AES);
// 利用用户密码作为随机数初始化出
gen.init(128, new SecureRandom((Optional.ofNullable(word).orElse("") + UUID.randomUUID()).getBytes()));
//加密没关系,SecureRandom 是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以解密只要有password就行
// 根据用户密码,生成一个密钥
SecretKey secretKey = gen.generateKey();
// 返回基本编码格式的密钥,如果此密钥不支持编码,则返
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
} catch (NoSuchAlgorithmException e) {
log.error("生成 AES key 失败:{}", e.getMessage(), e);
}
return null;
}

/**
* AES 加密
*
* @param content 待加密内容
* @param key 密钥
* @return 加密后结果(Base64编码)
*/
public static String aesEncrypt(String content, String key) {
return encrypt(content, Base64.getDecoder().decode(key), AES, null);
}


/**
* AES 解密
*
* @param content 内容(Base64编码)
* @param key 私钥
* @return 解密后数据
*/
public static String aesDecrypt(String content, String key) {
return decrypt(content, Base64.getDecoder().decode(key), AES, null);
}

public static String encrypt(String content, byte[] key, String algorithm, Provider provider) {
try {
Cipher cipher = provider == null
? Cipher.getInstance(algorithm)
: Cipher.getInstance(algorithm, provider);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, algorithm));
byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptStr);
} catch (Exception e) {
log.error("{} 数据加密失败:{}", algorithm, e.getMessage(), e);
return null;
}
}

public static String decrypt(String content, byte[] key, String algorithm, Provider provider) {
try {
byte[] encryptByte = Base64.getDecoder().decode(content);
Cipher cipher = provider == null
? Cipher.getInstance(algorithm)
: Cipher.getInstance(algorithm, provider);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, algorithm));
byte[] decryptBytes = cipher.doFinal(encryptByte);
return new String(decryptBytes);
} catch (Exception e) {
log.error("{} 数据解密失败:{}", algorithm, e.getMessage(), e);
return null;
}
}
}

本文地址: https://github.com/maxzhao-it/blog/post/e89f3b77/