写一个java密钥加密
时间: 2023-12-21 14:07:15 浏览: 30
以下是一个Java密钥加密的示例代码:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class KeyEncryptionExample {
public static void main(String[] args) throws Exception {
String plainText = "This is a secret message.";
// 生成一个随机密钥
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
// 加密
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes());
// 输出加密后的密文
System.out.println("Encrypted text: " + new String(encryptedTextBytes));
// 解密
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
// 输出解密后的明文
System.out.println("Decrypted text: " + new String(decryptedTextBytes));
}
}
该示例使用AES算法生成一个随机密钥,然后使用该密钥对某个字符串进行加密和解密。在实际应用中,密钥通常不是随机生成的,而是使用密钥管理系统等工具生成和管理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)