import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* 生成密钥
*
* @return 密钥
* @throws Exception 异常
*/
public static String generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGORITHM);
keyGen.init(128); // 可以选择128, 192或256位密钥长度
SecretKey secretKey = keyGen.generateKey();
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
}
/**
* 解密
*
* @param content 待解密内容
* @param key 密钥
* @return 解密后的内容
* @throws Exception 异常
*/
public static String decrypt(String content, String key) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(content);
byte[] raw = Base64.getDecoder().decode(key);
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
/**
* 加密
*
* @param content 待加密内容
* @param key 密钥
* @return 加密后的内容
* @throws Exception 异常
*/
public static String encrypt(String content, String key) throws Exception {
byte[] raw = Base64.getDecoder().decode(key);
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(content.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static void main(String[] args) {
try {
// 生成密钥
String key = generateKey();
System.out.println("Generated Key: " + key);
// 测试加密和解密
String originalContent = "Hello, World!";
String encryptedContent = encrypt(originalContent, key);
System.out.println("Encrypted Content: " + encryptedContent);
String decryptedContent = decrypt(encryptedContent, key);
System.out.println("Decrypted Content: " + decryptedContent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成密钥:
KeyGenerator 类生成一个 AES 密钥。加密:
Cipher 类进行加密操作。SecretKeySpec 对象。Cipher 对象为加密模式,并使用该对象对输入字符串进行加密。解密:
Cipher 类进行解密操作。SecretKeySpec 对象。Cipher 对象为解密模式,并使用该对象对输入的 Base64 编码字符串进行解密。测试:
main 方法中生成密钥,并测试加密和解密功能。上一篇:java arrays.sort
下一篇:java list对象排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站