import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
// 生成AES密钥
public static SecretKey generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128); // 可以选择128, 192或256位密钥长度
return keyGen.generateKey();
}
// 加密方法
public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密方法
public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
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 {
// 生成密钥
SecretKey secretKey = generateKey();
// 要加密的明文
String plainText = "Hello, AES Encryption!";
// 加密
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted: " + encryptedText);
// 解密
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成AES密钥:
KeyGenerator
类生成一个AES密钥。可以选择128、192或256位的密钥长度。加密方法:
Cipher
类进行加密操作。首先初始化 Cipher
对象为加密模式,并传入生成的密钥。然后将明文转换为字节数组并进行加密,最后将加密后的字节数组用Base64编码成字符串返回。解密方法:
Cipher
类进行解密操作。初始化 Cipher
对象为解密模式,并传入相同的密钥。将Base64编码的加密字符串解码为字节数组后进行解密,最后将解密后的字节数组转换为字符串返回。主程序:
这个示例展示了如何在Java中使用AES算法进行加密和解密操作。
上一篇:java实现aes的五种加密模式
下一篇:java判断字符串是否为纯数字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站