Thursday, November 22, 2012

Why Character Array is preferred over String for Storing password in Java

In this post, we'll see few reasons why char array is always preferred over String for storing password.

As you know, both string and char array is used to store textual data but choosing one over the other is more difficult. May be you can get the idea from the immutability of String why char array is preferred over string for storing the password.

1. With plain String you have much higher chance of accidentally printing the password to logs or some other insecure places. where char[] is less vulnerable. 
For example :
Output :

Since string is immutable i.e. there is no method defined that allow you to change or overwrite the content of string. This feature make string object unstable for storing the secure information such as user password.
You should always store or collect secure information in char [] array rather than string.

2. Since string is immutable if you store password as plain text it will be available in memory until Garbage collector clean it. Since string used string pool for re-usability of string, there will be pretty chance that it will remain in memory for long duration. 
Since any one who has access to memory dump can easily find the password in plain text that's the another reason use should use encrypt password than plain text.

3. The official document of Java Cryptography Architecture guide says about char [] vs string password

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.

4. If you notice in swing application, there is method of JPasswordField i,e  getPassword() which return char[] and the deprecated method getText() which return the password in plain text. So java itself recommending to use the getPassword() method.

5. Other reason for storing passwords in character array, because char[] can be sanitized, e.g. after usage one can override clear password with junk, while string is immutable in java

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...


  1. It's very clear, thanks for this post

  2. Nice information, never had think of this side effect of String immutability.