如何在Java函数中对文本进行加密和解密?
发布时间:2023-09-12 20:09:54
在Java中,可以使用一些现有的加密算法和库来对文本进行加密和解密。下面是一个简单的示例,展示了如何使用AES加密算法对文本进行加密和解密。
首先,需要导入javax.crypto库和相关的类:
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64;
加密函数如下:
public static String encrypt(String plainText, String encryptionKey) throws Exception {
// 创建Cipher对象
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 创建SecretKeySpec对象,并使用指定的加密密钥初始化
SecretKeySpec secretKey = new SecretKeySpec(encryptionKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 对明文进行加密
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
// 使用Base64编码将密文转换为字符串返回
return Base64.getEncoder().encodeToString(encryptedBytes);
}
解密函数如下:
public static String decrypt(String cipherText, String encryptionKey) throws Exception {
// 创建Cipher对象
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 创建SecretKeySpec对象,并使用指定的加密密钥初始化
SecretKeySpec secretKey = new SecretKeySpec(encryptionKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
// 使用Base64解码将密文转换为字节数组
byte[] cipherBytes = Base64.getDecoder().decode(cipherText);
// 对密文进行解密
byte[] decryptedBytes = cipher.doFinal(cipherBytes);
// 将解密后的字节数组转换为字符串返回
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
接下来,可以在主函数中进行加密和解密的测试,示例代码如下:
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String encryptionKey = "ThisIsASecretKey";
// 加密文本
String encryptedText = encrypt(plainText, encryptionKey);
System.out.println("Encrypted Text: " + encryptedText);
// 解密文本
String decryptedText = decrypt(encryptedText, encryptionKey);
System.out.println("Decrypted Text: " + decryptedText);
}
运行以上代码,将输出以下内容:
Encrypted Text: eb6G2BsfemP3p/KvHQFXHg== Decrypted Text: Hello, World!
以上是一个使用AES加密算法对文本进行加密和解密的简单示例。请注意,在实际使用中,应该使用更复杂和安全的加密算法,并确保密钥的安全存储和传输。
