Why is it better to use char[] than String for passwords?

Asked

Viewed 690 times

9

Using Swing, the method getPassword() of JPasswordField returns a character array char[] instead of returning a String like the getText() (which by the way is discontinued).

I should not use String to store passwords? Why char[] would be better? Security issues?

1 answer

13


This is about safety. If information stays longer than needed in memory it has a better chance of the application being compromised and someone with access to the machine can get the password.

Strings are immutable, you can not write about it if you want to change the content of a string, has to create another string new and discard this old one. The problem is that the actual discard will only occur when the Garbage Collector take action, and it can take a long time.

A char[] is changeable, so at any time you can reset the content of it. Even if it is not collected on time, having the values reset the password is not exposed any longer than necessary (i.e., a tiny fraction of a second).

  • So, logically, after using the password I must reset the array?

  • 1

    If you want something safe, yes, of course that’s just one aspect of security. It doesn’t mean you’re 100% second because you did this, but it’s one of the things that avoids a certain commitment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.