import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class JavaEncryptionExample {
// 生成密钥
public static SecretKey generateKey(int n) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(n);
SecretKey secretKey = keyGen.generateKey();
return secretKey;
}
// 加密方法
public static byte[] encrypt(String plainText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText.getBytes());
}
// 解密方法
public static String decrypt(byte[] cipherText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(cipherText));
}
public static void main(String[] args) {
try {
// 生成128位的密钥
SecretKey secretKey = generateKey(128);
// 要加密的文本
String originalText = "Hello, World!";
// 加密
byte[] encryptedText = encrypt(originalText, secretKey);
System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(encryptedText));
// 解密
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
KeyGenerator
类来生成一个 AES 算法的密钥。这里我们生成了一个 128 位的密钥。Cipher
类来进行加密操作,传入明文和密钥,返回加密后的字节数组。Cipher
类进行解密操作,传入加密后的字节数组和密钥,返回解密后的字符串。main
函数中,我们演示了如何生成密钥、加密和解密一个简单的字符串。这个例子展示了如何使用 Java 内置的加密库(如 javax.crypto
)来进行基本的加密和解密操作。
上一篇:java list 转array
下一篇:java list 交集
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站