Why prefer char[] array over String for Password

Sometimes we have to perform authentication in our application. Most of the times, we ask the user to provide the user id and password to validate them.


Why prefer Char[] array over String for Password?

We can store the password in a String variable. But, the char[] array is preferred over String to store password values. In this tutorial, we will look into some possible reasons to prefer char[] array over String to store password and other sensitive data.


1. Java String is immutable and cached in String Pool

Java String objects are immutable and stored in the string pool. So, once we create a string variable, there is no way to delete it. Even if the garbage collection kicks in, there is no guarantee that the string object will be removed from the pool. So, the password remains in the memory for longer period of time than it’s actually needed for.

If we use char[] array to store the password, we can rewrite the array value to remove the password content from the java runtime memory.

String pwd = "app$pwd"; // goes into string pool
pwd = ""; // doesn't remove the above string from the pool
		
char[] pwdC = {'a', 'p', 'p', '$', 'p', 'w', 'd'};
Arrays.fill(pwdC, '0'); // removed the password content from memory

2. Security issue

If someone has access to take the java memory dump, he can access the data stored in the string pool. This is a security risk and since we can’t remove strings from the pool ourself, the risk is even higher.

This risk is present with the char array too, but it’s reduced because we can remove the password content as soon as we are done with it.

This is a strong reason to use encrypted passwords in the application by using some hashing algorithms.


3. Avoiding Accidental Printing of Password in Logs

It’s a natural tendency to print variable contents to the log file for debugging purposes. If someone prints the string content mistakenly, it gets printed as the actual value. But, if we print the char array, it won’t print its content.

package net.javastring.strings;

public class PasswordStore {

	public static void main(String[] args) {

		String pwd = "abc";
		System.out.println("String password: " + pwd);

		char[] pwdC = { 'a', 'b', 'c' };
		System.out.println("Character password: " + pwdC);
	}
}

Output:

String password: abc
Character password: [C@3764951d

4. Java APIs also recommend use of char[] array

If you look at the Swing API JPasswordField getPassword() method, it returns a character array. The method also recommends that the returned character array be cleared after use by setting each character to zero.

In the initial Java versions, JPasswordField getText() method was used to return the password in the string format. Later on, the getPassword() method was introduced and getText() method was deprecated citing the security reasons.

References: