在Java中,HashMap本身不提供内置的加密功能。但是,您可以在将数据存储到HashMap之前对其进行加密,并在从HashMap中检索数据时进行解密。以下是一个使用AES加密和解密的示例:
首先,您需要添加Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files到您的项目中。这些文件可以从Oracle官网下载。下载并替换local_policy.jar
和US_export_policy.jar
文件。
接下来,创建一个加密和解密工具类:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class EncryptionUtil { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding"; public static SecretKey generateSecretKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM); keyGenerator.init(128); return keyGenerator.generateKey(); } public static String encrypt(String data, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decodedBytes = Base64.getDecoder().decode(encryptedData); return new String(cipher.doFinal(decodedBytes)); } }
现在,您可以使用此工具类对HashMap中的数据进行加密和解密:
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { try { // 生成密钥 SecretKey secretKey = EncryptionUtil.generateSecretKey(); // 创建一个HashMap MaphashMap = new HashMap<>(); // 添加加密数据到HashMap hashMap.put("key1", EncryptionUtil.encrypt("value1", secretKey)); hashMap.put("key2", EncryptionUtil.encrypt("value2", secretKey)); // 从HashMap中获取加密数据并解密 String decryptedValue1 = EncryptionUtil.decrypt(hashMap.get("key1"), secretKey); String decryptedValue2 = EncryptionUtil.decrypt(hashMap.get("key2"), secretKey); System.out.println("Decrypted value1: " + decryptedValue1); System.out.println("Decrypted value2: " + decryptedValue2); } catch (Exception e) { e.printStackTrace(); } } }
请注意,这个示例使用了ECB模式进行加密,它可能不适用于所有场景。在实际应用中,建议使用更安全的模式,如CBC或GCM。同时,确保密钥的安全存储和传输。