Java实现AES简要代码包括生成随机密钥
时间: 2024-04-23 21:23:17 浏览: 77
以下是Java实现AES加密和解密并生成随机密钥的简要代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* 生成随机密钥
*
* @return 密钥
*/
public static String generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
byte[] encoded = secretKey.getEncoded();
return Base64.getEncoder().encodeToString(encoded);
}
/**
* AES加密
*
* @param content 需要加密的字符串
* @param key 密钥
* @return 加密后的字符串
*/
public static String encrypt(String content, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* AES解密
*
* @param content 需要解密的字符串
* @param key 密钥
* @return 解密后的字符串
*/
public static String decrypt(String content, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(content));
return new String(decrypted, StandardCharsets.UTF_8);
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) throws Exception {
String content = "Hello, world!";
// 生成随机密钥
String key = AESUtil.generateKey();
System.out.println("生成的密钥:" + key);
// 加密
String encrypted = AESUtil.encrypt(content, key);
System.out.println("加密后的字符串:" + encrypted);
// 解密
String decrypted = AESUtil.decrypt(encrypted, key);
System.out.println("解密后的字符串:" + decrypted);
}
}
```
阅读全文