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开发者_StackOverflow中文版 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?
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.
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).
A String is an immutable class, and when the password is stored in a String you have no control over its life cycle, which means it can be available in memory (and subject to memory dumps and the like) for a long time (even if it is not interned, where it would be in memory until the JVM exits). When it is stored in a character array, you can clear the array and thus remove the password from memory once you have validated it.
精彩评论