I have a problem with storing a plain password in memory as a String. According to the reference, since Strings are immutable there is a vulnerability of using String data type for sensitive data storing in memory.
https://www.geeksforgeeks.org/use-char-array-string-storing-passwords-java/
Why is char[] preferred over String for passwords?
Can I overcome this security issue by nullifying the string variable instead of using char array or String buffer/builder.
eg : String password="password"; password = null;
No. Nullifying a string would only delink the reference. But the value will still exist in string pool. Because to conserve memory, string values are retained in the string pool.
Any potential hacker, can retrieve the value by gaining access to the string pool.
Whereas, using char[], you can simply treat that object as any other object. And nullifying the char object will wipe off the data from heap at the time of garbage collection.
An even better option will be using a byte array.
Read more about String Constant pool.
If you want absolute security, no. Nulling out the String is not the right solution.
The reason for this is that nulling it out makes no guarantees about the String no longer being available. Although it may make it more likely to be garbage collected (and this is only a 'may'), there are no guarantees about when (or even if) it will be garbage collected.
You should use either a byte array, or a char array, and then null each of the elements in the array when you are done.
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