Question

Since Java 1.2, JPasswordField.getText() has been deprecated "for security reasons", ecouraging usage of getPassword() method "for stronger securty".

However, I was able to get the password stored in JPasswordField at least in Oracle JRE 1.7 by analysing the heap dump (JPasswordField instance -> model -> s -> array).

So how does JPasswordField.getPassword() helps to protect the password?

Was it helpful?

Solution

Well, the documentation for it states:

For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.

But, of course, if you use the getText method, you get back a String, which is immutable, so you couldn't carry out the same recommendation.

OTHER TIPS

Security note though getPassword() uses getText() internally

Although the JPasswordField class inherits the getText method, you should use the getPassword method instead. Not only is getText less secure, but in the future it might return the visible string (for example, "**") instead of the typed string.

To further enhance security, once you are finished with the character array returned by the getPassword method, you should set each of its elements to zero.

The answer is simple. Here is a pragmatic approach that explains the difference between getPassword() and getText()

JPasswordField jt=new JPasswordField("I am a password");
System.out.println("The text is "+jt.getText());
System.out.println("The password is "+jt.getPassword());

Output

I am a password
[C@1e4a47e

The getPassword() method returns the password as char[] whereas the getText() returns the password as plain text i.e. in the form of String.

However, if you do print like this,

System.out.println(new String(jt.getPassword()));

This is much equal to getText() in JPasswordField. However this does not mean that getPassword() uses the getText() internally and then convert it into char array.

The getPassword() method uses the non-string API i.e. the Segment. However, Segment is again immutable, but the getPassword() method brings the char array from the Segment and returns it.

However as String is immutable and char[] is not, a char[] is considered quite secure because it can be wiped out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top