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, ""?
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.
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.
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.
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[].
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.
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