I'm working on some application that works with secret data in memory. Is there a way to make sure all the memory is overwritten when the JVM terminates? Nothing of the secret data should be left in memory after the termination of the JVM.
Short answer: current generation JVMs cannot guarantee that.
However, if your application is such that it requires this kind of thing, it is difficult to see how you could implement it in any programming language on a typical modern operating system unless you ran without a swap device. And even then, you would probably need to rely on the OS to zero physical memory on program exit. (Unless there are bugs, the OS should zero memory before giving it to another process, but I don't think it is specified when that happens.)
But this is moot. The operating system should prevent unauthorized people / processes from seeing the memory of other processes, either during the program's execution or after it exits. If your system has been hacked to gain "root" privilege or equivalent, you can't guarantee either of those. So by the time the program exits, it is already too late!
You cannot delete all secret data on JVM termination. In case of compacting collector (i.e all modern collectors), it may copy data from one location to another. Hence when you overwrite your array, the data would still exist in the old location, but you won;t have any reference to it so you cannot overwrite it.
The best you can do is to overwrite the current location (if you store the data in arrays) and hold it in memory for as little time as possible, to minimize the chance (but you cannot avoid it on 100%) that secret data will remain in the heap during compaction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With