【发布时间】:2013-10-16 18:01:02
【问题描述】:
我的问题是我正在解密/加密来自不同线程的一些随机值字符串集,但经过多次迭代后内存迅速增加。
我的观察是内存增加是因为每次加密/解密都会产生新的字符串,因此内存会增加。
还有一点需要注意的是我的解密/加密字符串会有很多与相同的字符串集相同的值(某些字符串可能是新的)从许多线程中加密/解密,但由于在每个加密/解密中,密码返回字节数组并再次构成字符串,我必须使用“新字符串()”函数,这可能会或将迅速增加内存。
这是我加密/解密字符串的代码
public static String encrypt(String key, String value) throws GeneralSecurityException
{
byte[] raw = key.getBytes();
if (raw.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
byte[] cipherBytes= cipher.doFinal(value.getBytes());
byte[] encoded = org.apache.commons.codec.binary.Base64.encodeBase64(cipherBytes);
return new String(encoded);
}
public static String decrypt(String key, String encrypted) throws GeneralSecurityException
{
byte[] raw = key.getBytes();
if (raw.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
byte[] byteDecodedText = org.apache.commons.codec.binary.Base64.decodeBase64(encrypted.getBytes()) ;
byte[] original = cipher.doFinal(byteDecodedText);
return new String(original);
}
【问题讨论】:
-
您可以在从字节数组中提取
String后立即调用intern(),并删除对String的所有引用。当然,String会占用内存,直到它被垃圾回收,但我看不出你能做得比这更好。 -
@DavidWallace 这意味着我必须在 new String(byteDecryptedText) 上调用实习生;
-
是的,很明显。但无论如何,您将不得不致电
new String(byteDecryptedText)。 -
@DavidWallace 我这样做了,但没有改善同样的内存峰值。
-
我们不要在聊天中继续讨论。现在是凌晨 1 点。我需要去睡觉。也许其他人可以帮助你。或者你可以等我醒来。
标签: java string encryption