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


Using Swing, the getPassword() method of JPasswordField returns an array of char[] characters instead of returning String as getText() (which by the way is deprecated).

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

asked by anonymous 04.09.2017 / 19:26

1 answer


It's about safety. If information gets longer than necessary in memory, it is more likely that the application will be compromised and someone with access to the machine can pick up the password.

Strings are immutable, you can not write about it, if you want to change the contents of a string , you have to create another new string and discard this old one. The problem is that the actual disposal will only occur when the garbage collector takes effect, and can take a long time.

A char[] is changeable, so at any time you can zero the contents of it. Even if it is not collected at the time, having the values reset the password will not be exposed for longer than necessary (that is, a tiny fraction of a second).

04.09.2017 / 19:31