Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to nullifying String in java [duplicate]

Tags:

java

string

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;

like image 559
Sudesh Chandana Avatar asked Mar 13 '18 06:03

Sudesh Chandana


2 Answers

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.

like image 128
tryingToLearn Avatar answered Oct 19 '22 06:10

tryingToLearn


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.

like image 21
chamakits Avatar answered Oct 19 '22 05:10

chamakits