What are the security reasons for JPasswordField.getPassword ()?

Since Java 1.2, JPasswordField.getText() deprecated "for security reasons," this encourages the use of the getPassword() method for stronger security. "

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

So how JPasswordField.getPassword() help protect your password?

+4
source share
3 answers

Well, the documentation for it states:

For greater 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 return a String that is immutable, so you cannot follow the same recommendation.

+3
source

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 smaller, but in the future it may return a visible string (for example, ** ") instead of the entered string.

To further enhance security, as soon as you finish with the character the array returned by the getPassword method, you must set each of its elements to zero.

+1
source

The answer is simple. Here is a pragmatic approach explaining 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[] , while getText() returns the password as plain text, i.e. in the form of a String .

However, if you print like this,

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

This is a lot equal to getText() in JPasswordField . However, this does not mean that getPassword() uses getText() internally and then converts it to a char array.

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

However, since String is immutable and char[] not, a char[] is considered quite safe since it can be erased.

+1
source

Source: https://habr.com/ru/post/1389639/


All Articles