pau.minoves
pau.minoves

Reputation: 28

How can I securely delete an object in Java from code?

In Java, When having objects that you need to securely dispose of, which are the options?

Taking into account that:

a) The when: You need some guarantee on when the object is disposed. Is calling System.gc() the only/better option?

b) The how: GC is not enough and you need to make sure the memory an object instance is using is properly erased. One can first get references to the internal object representation via reflection (get char[] inside a String) and overwrite the data. However, this method requires an implementation for each type of object.

Are there better ways to make sure that passwords and private key objects are not left on RAM?

Update: Passwords are an example. This question focuses on general methods for object secure destruction. Think BigInteger, PGPPrivateKey, RSAWhatever, etc.

Upvotes: 1

Views: 2197

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533670

I would use off heap memory so it won't appear in any heap dump, and won't be copied around (even if you clear char[] an old copy could still be readable) Once you overwrite it you know where won't be another copy somewhere.

Off heap memory is harder to work with as you have to deal in primitives, but it is easy to zero out as you can just overwrite everything in it.

Upvotes: 2

nanofarad
nanofarad

Reputation: 41281

Disclaimer: This uses reflection and may not be the nicest way.

However, this method requires an implementation for each type of object.

No, not really. You can iterate through fields and destroy those, or even traverse an entire object graph. The first step to go would be primitives and arrays of primitives, and nulling out object references that are fields of the object you are trying to "shred". In fact, that last step could be done recursively with a null-check.

Upvotes: 2

Bohemian
Bohemian

Reputation: 425198

You can't rely on garbage collection to remove your object from memory; calling System.gc() doesn't cause gc to run - it just "asks nicely". It could hang around for a while in memory.

The standard approach is to use an object that can be wiped before disposal, like char[] instead of String:

char[] password = <read password from input stream etc>
// check password
Arrays.fill(password, 'x');
// password available for gc, but now wiped

This only reduces the time that the password is in memory. It doesn't eliminate it. If someone got a memory dump at the right time they may be able to find the bytes. If you secure your server well, getting the dump should be difficult to impossible in the first place.

Upvotes: 1

Related Questions