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

可紊 提交于 2021-02-07 11:48:41

问题


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?


回答1:


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.




回答2:


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).




回答3:


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.



来源:https://stackoverflow.com/questions/3451211/java-console-readpassword-how-does-an-array-protect-from-determining-the-passw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!