import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class EncryptionDecryptionUtil {
private static final String ALGORITHM = "AES";
// 生成密钥
public static String generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(128); // 设置密钥长度为128位
SecretKey secretKey = keyGen.generateKey();
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
}
// 加密方法
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedData = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encryptedData);
}
// 解密方法
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedData, "UTF-8");
}
public static void main(String[] args) {
try {
// 测试加密解密工具类
String key = generateKey();
System.out.println("Generated Key: " + key);
String originalData = "Hello, World!";
String encryptedData = encrypt(originalData, key);
System.out.println("Encrypted Data: " + encryptedData);
String decryptedData = decrypt(encryptedData, key);
System.out.println("Decrypted Data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成密钥:
KeyGenerator 类生成 AES 算法的密钥,密钥长度为 128 位。加密方法:
SecretKeySpec 和 Cipher 类进行加密操作。解密方法:
SecretKeySpec 和 Cipher 类进行解密操作。测试代码:
main 方法中,生成密钥并测试加密和解密功能。上一篇:aes加密 java
下一篇:java判断字符串是否为纯数字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站