import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class JavaAESEncryptionDecryption {
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
// 生成密钥
public static String generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(KEY_SIZE);
SecretKey secretKey = keyGen.generateKey();
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
}
// 加密方法
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
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(Base64.getDecoder().decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
public static void main(String[] args) {
try {
// 生成密钥
String key = generateKey();
System.out.println("Generated Key: " + key);
// 要加密的文本
String originalText = "Hello, World!";
System.out.println("Original Text: " + originalText);
// 加密
String encryptedText = encrypt(originalText, key);
System.out.println("Encrypted Text: " + encryptedText);
// 解密
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成密钥:
KeyGenerator
类生成一个 AES 密钥,并将其编码为 Base64 字符串,方便存储和传输。加密方法:
Cipher
类进行加密。首先将 Base64 编码的密钥解码为字节数组,然后创建 SecretKeySpec
对象。Cipher
为加密模式,并使用生成的密钥对明文进行加密。解密方法:
Cipher
类进行解密。先将 Base64 编码的密钥解码为字节数组,再创建 SecretKeySpec
对象。Cipher
为解密模式,并使用生成的密钥对加密后的文本进行解密。主程序:
这样就完成了一个完整的 AES 加密解密过程。
上一篇:java面向对象
下一篇:java字符串拼接
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站