-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathAES.java
More file actions
48 lines (36 loc) · 1.66 KB
/
AES.java
File metadata and controls
48 lines (36 loc) · 1.66 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
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.util.Base64;
public class AES {
public static String encrypt(String plainText, String key) throws Exception {
// 创建密钥
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
// 创建加密器
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 加密
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String key) throws Exception {
// 创建密钥
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
// 创建解密器
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
// 解密
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String key = "1234567890123456"; // 16字节密钥
System.out.println("原文: " + plainText);
String encrypted = encrypt(plainText, key);
System.out.println("加密后: " + encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("解密后: " + decrypted);
System.out.println("验证: " + plainText.equals(decrypted));
}
}