在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
Map<String, String> hashMap = 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。同時,確保密鑰的安全存儲和傳輸。