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


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



  1. Replies

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

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