java对称加密解密怎么操作
问题描述:java对称加密解密怎么操作
推荐答案 本回答由问问达人推荐
在Java中,可以使用javax.crypto包提供的加密算法和密钥库来进行对称加密和解密操作。对称加密使用相同的密钥同时进行加密和解密,因此需要安全地管理密钥以确保数据的保密性。下面是一个使用对称加密算法进行加密和解密的示例代码:
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 SymmetricEncryption {
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String encryptionKey = "SecretKey";
byte[] encryptedData = encrypt(plainText, encryptionKey);
System.out.println("Encrypted Data: " + Base64.getEncoder().encodeToString(encryptedData));
String decryptedText = decrypt(encryptedData, encryptionKey);
System.out.println("Decrypted Text: " + decryptedText);
}
public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
SecretKeySpec secretKey = generateKey(encryptionKey);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return encryptedData;
}
public static String decrypt(byte[] encryptedData, String encryptionKey) throws Exception {
SecretKeySpec secretKey = generateKey(encryptionKey);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData = cipher.doFinal(encryptedData);
return new String(decryptedData, StandardCharsets.UTF_8);
}
public static SecretKeySpec generateKey(String encryptionKey) throws Exception {
byte[] keyBytes = encryptionKey.getBytes(StandardCharsets.UTF_8);
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
return new SecretKeySpec(keyBytes, "AES");
}
}
上述代码使用AES算法进行对称加密和解密。首先,通过generateKey方法生成AES密钥,然后使用该密钥初始化加密和解密的Cipher对象。encrypt方法将明文字符串转换为字节数组后进行加密,返回加密后的字节数组。decrypt方法对加密后的字节数组进行解密并返回解密后的明文字符串。
注意:在实际应用中,密钥的生成和管理应该更加安全可靠,并且考虑使用随机生成的密钥。
查看其它两个剩余回答