Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Console; readPassword, how does an array protect from determining the password value?

I was reading about the java.io.Console class in one of the java certification books, possibly I've missed something fundamental from a previous chapter, but can someone explain the below?

It mentions, that the readPassword method returns a character array instead of a String, to prevent a potential hacker from finding this String and then finding the password.

How is a character array safer? If you could obtain the values in the array then could you not create a script to loop through various combinations and eventually find the password anyway?

like image 251
Jimmy Avatar asked Aug 10 '10 16:08

Jimmy


2 Answers

From the documentation:

The Console object supports secure password entry through its readPassword method. This method helps secure password entry in two ways. First, it suppresses echoing, so the password is not visible on the user's screen. Second, readPassword returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.

The idea here is that you can call Arrays.fill (or equivalent) to "blank" the char array as soon as you've validated the password, and from that point the password is no longer stored in memory. Since Strings are immutable, the String will remain in the heap until it is garbage collected - which if it manages to get itself interned will be never, and in any other case could still be "too long". All the while it is there, it's potentially vulnerable to sniffing from a variety of vectors.

like image 140
Andrzej Doyle Avatar answered Oct 12 '22 06:10

Andrzej Doyle


It's one of those best practice things. It doesn't make a great deal of sense, but we do it for an easy life.

If a password is in memory, a buffer read overflow could allow it to be read. Or it could be saved in a core dump or hibernation image. Using a mutable char[] allows the data to be destroyed, after a hopefully narrow window, so long as it hasn't been copied into a string, copied elsewhere, it's probably in buffers, garbage collection likes to move objects, etc.

There is an amusing example in Swing, where JPasswordField provides a char[] way to read the data, but for instance will create a String from the data if it has an action listener (which is a very common way to use it).

like image 41
Tom Hawtin - tackline Avatar answered Oct 12 '22 05:10

Tom Hawtin - tackline