在Java中,使用javax.crypto
包中的Cipher
类可以帮助你加密和解密敏感数据。以下是一个简单的示例,展示了如何使用AES加密算法保护敏感数据:
首先,确保已经安装了Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files。这些文件可以从Oracle官方网站下载。安装后,Java将支持更强大的加密算法,如AES-256。
导入所需的类:
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 static SecretKey generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256); // 设置密钥长度为256位
return keyGenerator.generateKey();
}
public static String encrypt(String data, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedData);
}
public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData, StandardCharsets.UTF_8);
}
public static void main(String[] args) {
try {
SecretKey secretKey = generateKey();
String sensitiveData = "This is some sensitive data";
System.out.println("Original data: " + sensitiveData);
String encryptedData = encrypt(sensitiveData, secretKey);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = decrypt(encryptedData, secretKey);
System.out.println("Decrypted data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
运行此程序,你将看到原始数据、加密后的数据和解密后的数据。请注意,为了安全地存储和传输密钥,你需要采取额外的措施,例如使用密钥管理系统或将其存储在安全的硬件设备上。