问题
I am using Java AES encryption using
SecretKeySpec(byte[] key, String algorithm)
to generate a Key object.
After I encrypt something, I want to remove the Key from memory.
I can remove all references to the Key, but that does not guarantee that the key is not floating somewhere in memory.
I can "zero out" the byte[] array that I used to generate the Key, but how can I zero out or flush the actual Key memory.
回答1:
There doesn't appear to be a way to do this in Java versions up to 7, but it has been fixed for Java 8 by adding the Destroyable
interface.
See https://bugs.openjdk.java.net/browse/JDK-6263419
Addess this requirement by enhancing java.security.PrivateKey and javax.crypto.SecretKey classes to extend the javax.security.auth.Destroyable interface.
However, note the comments:
clearing out a BigInteger or byte[] reference doesn't guarantee that the sensitive information is gone from memory. The operating system's virtual memory may have been swapped to disk, for example, leaving a copy on the local hard drive. In addition, the Java runtime VM may itself have multiple internal copies of the information.
Note also that zeroing out the original byte array will NOT clear the SecretKeySpec, because it takes a copy of the byte array in its constructor.
However, you might be able to get access to the SecretKeySpec copy of the byte array (even though it is private) using Java Reflection to change the access to that field.
回答2:
If Java 8 isn't available to you, you're going to need to be a little creative. Namely, picking the correct tool for the job. In this case, I'd recommend C. C gives you complete access to the actual memory; Java abstracts almost all of that away from you. So the explanation would be as follows:
- Obtain the memory address of the object. This can be taken using this code.
- Using this memory address, pass it to a C program. You can then create a variable at that memory address.
- Manually zero out the memory address.
As is pointed out in the comments, there are more implementation level details that arise. The point of this answer is to highlight that other languages do this much better and it might be worth looking into.
来源:https://stackoverflow.com/questions/28907297/how-to-zero-out-from-memory-an-aes-secretkeyspec-key-in-java