Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char[] or StringBuilder for passwords?

So, because Strings are immutable, we use char[] instead of String to store passwords so that we can erase the characters when we're done with it. Is StringBuilder (or StringBuffer) as safe as a char[] in this case because one can change to value of the password to, say, ""?

like image 812
Michael Avatar asked Oct 18 '11 16:10

Michael


People also ask

Why char [] are preferred for passwords over strings?

Since Strings are immutable there is no way the contents of Strings can be changed because any change will produce a new String, while if you use a char[] you can still set all the elements as blank or zero. So storing a password in a character array clearly mitigates the security risk of stealing a password.

Will you store password in String or char array?

We should always store the secure information in char[] array rather than String. Since String is immutable if we store the password as plain text it will be available in memory until the garbage collector cleans it.

What is the best way to store passwords in Java?

Currently, the most secure way to store passwords is using Password Based Encryption (PBE), which provides functions (called Key Derivation Functions (KDFs)) that will convert low entropy user passwords into random, unpredictable, and most importantly one-way, irreversible bytes of data.

Which data type is most suitable for a password field in Java?

String for manipulating passwords, it's recommended by Java team themselves to use char[] instead. For instance, if we have a look at the JPasswordField of javax. swing, we can see that the method getText() which returns String is deprecated since Java 2 and is replaced by getPassword() method which returns char[].


1 Answers

No, because when you overflow the char[] used by the StringBuilder, it is replaced by a larger array, but the original array (with part of your password in it) remains in memory until it is garbage-collected.

like image 136
finnw Avatar answered Sep 24 '22 00:09

finnw