Possible Duplicate:
Why is char[] preferred over string for passwords?
I read somewhere that storing a sensitive key as a char[] rather than a String is better because the latter can be found in the memory. It also makes a little sense because of JPasswordField's getText() method being Deprecated.
Is this true?
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.
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. 2.
Strings are immutable: Strings are immutable in Java and therefore if a password is stored as plain text it will be available in memory until Garbage collector clears it and as Strings are used in the String pool for re-usability there are high chances that it will remain in memory for long duration, which is a ...
Below are the main reason to choose char datatype to store sensitive information, like password.
Once you are done using the password in a char[]
you can always overwrite it with 0's or random values. However, you can't do that with String
objects because they are immutable objects in Java and the strings will remain alive until the garbage collector kicks in and clears it.
Here is an interesting note at http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
In this example, we prompt the user for a password from which we derive an encryption key.
It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.
For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array.
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