Forcibly clear memory in java
- by MBennett
I am writing an application in java that I care about being secure. After encrypting a byte array, I want to forcibly remove from memory anything potentially dangerous such as the key used. In the following snippet key is a byte[], as is data.
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encData = cipher.doFinal(data, 0, data.length);
Arrays.fill(key, (byte)0);
As far as I understand, the last line above overwrites the key with 0s so that it no longer contains any dangerous data, but I can't find a way to overwrite or evict secretKeySpec or cipher similarly.
Is there any way to forcibly overwrite the memory held by secretKeySpec and cipher, so that if someone were to be able to view the current memory state (say, via a cold boot attack), they would not get access to this information?