import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class StringEncryptionExample {
// 生成密钥
public static byte[] generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128); // 可以选择128, 192或256位密钥长度
SecretKey secretKey = keyGen.generateKey();
return secretKey.getEncoded();
}
// 加密字符串
public static String encrypt(String plainText, byte[] key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密字符串
public static String decrypt(String encryptedText, byte[] key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
}
public static void main(String[] args) {
try {
// 生成密钥
byte[] key = generateKey();
// 原始字符串
String originalString = "Hello, World!";
System.out.println("Original: " + originalString);
// 加密
String encryptedString = encrypt(originalString, key);
System.out.println("Encrypted: " + encryptedString);
// 解密
String decryptedString = decrypt(encryptedString, key);
System.out.println("Decrypted: " + decryptedString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成密钥:
KeyGenerator 类生成一个 AES 密钥。密钥长度可以选择 128、192 或 256 位。加密字符串:
Cipher 类对字符串进行加密。加密算法为 AES,加密后的字节数组使用 Base64 编码转换为字符串,以便于传输和存储。解密字符串:
Cipher 类对加密后的字符串进行解密。解密后的字节数组转换回原始字符串。主函数:
这个示例展示了如何使用 Java 的 javax.crypto 包来进行字符串的加密和解密操作。
上一篇:java 邮件发送
下一篇:java调用接口
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站