15
15
public final class FastAes {
16
16
17
17
private static final String TRANSFORMATION = "AES/GCM/NoPadding" ;
18
- private static final int AES_KEY_LEN = 128 ; // bit
19
- private static final int GCM_TAG_LEN = 128 ; // bit
20
- private static final int GCM_IV_LEN = 12 ; // byte
18
+ private static final int AES_KEY_LEN = 128 ; // bit
19
+ private static final int GCM_TAG_LEN = 128 ; // bit
20
+ private static final int GCM_IV_LEN = 12 ; // byte
21
21
22
22
private static final SecureRandom RAND = new SecureRandom ();
23
23
@@ -30,12 +30,15 @@ public final class FastAes {
30
30
}
31
31
});
32
32
33
- private FastAes () {} // utility class
33
+ private FastAes () {
34
+ } // utility class
34
35
35
36
/* ---------------------------------- 对外 API ---------------------------------- */
36
37
37
38
/**
38
39
* 随机生成 AES-128 密钥
40
+ *
41
+ * @return 密钥
39
42
*/
40
43
public static SecretKey generateKey () {
41
44
try {
@@ -49,6 +52,9 @@ public static SecretKey generateKey() {
49
52
50
53
/**
51
54
* 将原始密钥字节数组包装成 SecretKey
55
+ *
56
+ * @param rawKey 原始密钥字节数组
57
+ * @return SecretKey
52
58
*/
53
59
public static SecretKey restoreKey (byte [] rawKey ) {
54
60
if (rawKey .length != AES_KEY_LEN / 8 ) {
@@ -59,6 +65,10 @@ public static SecretKey restoreKey(byte[] rawKey) {
59
65
60
66
/**
61
67
* 加密:返回 byte[],格式为 IV(12B) + CipherText + Tag(16B)
68
+ *
69
+ * @param key 密钥
70
+ * @param plain 原文
71
+ * @return 密文字节数组
62
72
*/
63
73
public static byte [] encrypt (byte [] plain , SecretKey key ) {
64
74
try {
@@ -71,16 +81,20 @@ public static byte[] encrypt(byte[] plain, SecretKey key) {
71
81
byte [] cipherText = cipher .doFinal (plain );
72
82
73
83
return ByteBuffer .allocate (iv .length + cipherText .length )
74
- .put (iv )
75
- .put (cipherText )
76
- .array ();
84
+ .put (iv )
85
+ .put (cipherText )
86
+ .array ();
77
87
} catch (Exception e ) {
78
88
throw new RuntimeException ("Encrypt error" , e );
79
89
}
80
90
}
81
91
82
92
/**
83
93
* 解密:输入格式须为 IV(12B) + CipherText + Tag(16B)
94
+ *
95
+ * @param key 密钥
96
+ * @param ivPlusCipherText 密文
97
+ * @return 原文
84
98
*/
85
99
public static byte [] decrypt (byte [] ivPlusCipherText , SecretKey key ) {
86
100
try {
@@ -104,7 +118,6 @@ public static byte[] decrypt(byte[] ivPlusCipherText, SecretKey key) {
104
118
}
105
119
}
106
120
107
- /* ----------------------------- 简易 Base64 封装 ----------------------------- */
108
121
109
122
public static String encryptToBase64 (byte [] plain , SecretKey key ) {
110
123
return Base64 .getEncoder ().encodeToString (encrypt (plain , key ));
0 commit comments