Why is char[] preferred over String for passwords?

Why is char[] preferred over String for passwords?

Problem

In my code I'm working on, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Likewise, I came across a suggestion not to use String to handle passwords.

Why is String a security risk when it comes to passwords? Using char[] is inconvenient.

Solution

Strings are immutable. This means that after creating a String, if another process can dump memory, there is no way (other than reflection) to get rid of the data before garbage collection begins.

You can explicitly wipe the data with the array when you're done with it. You can overwrite the array with whatever you want and the password won't be present anywhere on the system, even before you throw away the garbage.

So yes, it is a security issue - but even using char[] only limits the window of opportunity for the attacker, and only for that particular type of attack.

It is possible that the arrays carried by the garbage collector will leave stray copies of the data in memory. I believe this is implementation specific - the garbage collector can wipe all memory to avoid this sort of thing. Even so, there is still a time when char [] contains actual characters as an attack window.

Thanks to the regular string, you have a much better chance of accidentally printing the password to logs, monitors or other unsecured place. char [] is less vulnerable to attacks. Check example code:

public static void main(String[] args) {
    Object pw = "Password";
    System.out.println("String: " + pw);

    pw = "Password".toCharArray();
    System.out.println("Array: " + pw);
}

Share this Post