Sep 23, 2014

Why use char array for password?


What data structure do you use when to hold passwords in memory? String or character array??

Generally, I have seen peoples using String to store passwords in memory. This is fine, but it can lead to security threat. Any person having access to the heap dump can steal your password. You can argue that passwords are generally encrypted, so even if a person have access to the heap dump, he wont be able to get any useful information about the password. But, as String is immutable, even encrypting and assigning to the same reference would not change the content of previously occupied memory. If someone takes the heap dump before previous object gets garbage collected, he can have the actual password.


On the contrary, data at the same location of the char array can be modified without making a copy. Thus, if you store password in a char array, passwords content can be encrypted and data at same memory location can be overridden by the encrypted data.

Adding to the above, following may reasons may encourage you to store passwords in char[] rather String.
  1. There are always chances of accidentally logging the Strings in the log files whereas logging char[] would only result in garbage data.
  2. Java also recommends to use char array for passwords. It is evident from the getPassword() method of JPasswordField class. It returns char array as you can see in the link.
Hopefully above explanation helps. Please post your comments for any query.

4 comments:

  1. Very important piece of info Manoj.. After reading your post I actually tried something with String an character array.. And yep you are correct..

    ReplyDelete
  2. Nice article. Thanks for sharing. :)

    ReplyDelete