Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java storing sensitive 'key' as String or char[]? [duplicate]

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?

like image 793
LanguagesNamedAfterCofee Avatar asked Aug 17 '12 21:08

LanguagesNamedAfterCofee


People also ask

Which data type is best for storing password in Java?

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.

Why is it safer to store passwords in a char [] array rather than a string?

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.

Is it safe to store password in string?

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 ...

Which datatype is most suitable for a sensitive field?

Below are the main reason to choose char datatype to store sensitive information, like password.


1 Answers

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.

like image 130
Susam Pal Avatar answered Sep 20 '22 06:09

Susam Pal