Why Use Char Array Over A String For Storing Passwords In Java

Posted By : Ankur Bansala | 09-Jun-2018

 

Why Use char[] Array Over a Sting for Storing Passwords in Java?

In this blog, we will find the explanation of why we use array of char[] type to store passwords instead of using String in Java.

 

Most of us use object of type java.lang.String for storing passwords and it obvious, also notice that Java team has recommended themselves to use the array of char[] type instead.

 

 

 

For Ex:

If we took the password field of javax.swing, the method getText() returns String and this method is deprecated since Java 2 and also replaced by getPassword() method and it returns char[].

In this blog, we’ll look out on some point with reasons why that’s the case.

 

 

Strings are Immutable

 

We all know that in Java Strings are immutable. If you perform Any change on a String object it will produce a new String, and also by keeping the old one in memory.

 

So, If the password stored in a String will also be present in memory until Garbage Collector runs and clears it.

There is a fact that we cannot control the Gc to do so, but this can be longer than for regular objects since Strings are kept in a String Pool for re-usability purpose.

Therefore, anyone who has the access to the memory dump can retrieve or get the password from memory.

 

In case of char[] array, we can explicitly wipe out the data after we have finished with our work. So now, we will ensure that password is removed from memory and before garbage collection runs.

 

Accidentally Print Passwords

Many times we print the passwords in the log just for our reference but somehow we forgot to remove that log, in this case, char[] having an advantage of storing passwords in char[] array instead of String.

 

Let’s check the code:

 

String passwordString = "password";
char[] passwordArray = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
System.out.println("Printing String password -> " + passwordString);
System.out.println("Printing char[] password -> " + passwordArray);

 

With the output:

 

Printing String password -> password
Printing char[] password -> [C@6e8cf4c6

 

Here, We see that in the first case value itself is printed, while in the second case, We see that the data is not much useful, so char[] is less vulnerable over String.

Conclusion

 

In this short blog, we have gone through several reasons why we should not use Strings for storing passwords and why we should use char[] arrays instead.

I hope this will help you to explore further.

 

About Author

Author Image
Ankur Bansala

Ankur is an experienced Java back-end Developer and having capabilities to build web application.

Request for Proposal

Name is required

Comment is required

Sending message..