Question

I never thought before, only I used the method getPassword that returning an array of characters and I had seen the getText method was deprecated. But now that I think, why this method was deprecated?.

The Java documentation explains:

Deprecated. As of Java 2 platform v1.2, replaced by getPassword.

Fetches a portion of the text represented by the component. Returns an empty string if length is 0.

For security reasons, this method is deprecated. Use the getPassword method instead.

But what are those security reasons? Any ideas about this?

Thank you in advance.

Was it helpful?

Solution

When calling getText you get a String (immutable object) that may not be changed (except reflection) and so the password stays in the memory until garbage collected.

When calling getPassword you get a char array that may be modified, so the password will really not stay in memory.

OTHER TIPS

Try this :

String myPass=String.valueOf(passwordField.getPassword());

The reason for this is that if you ask for the password as a String rather than as a character array, this string containing the password is now going to float around in the Java runtime's memory for some unspecified amount of time. It may be conceivably read from there by a rogue Java component or external program.

By using a char array instead, you can verify the password and then scramble it immediately.

The reason behind this behavior is the Java String pool (see e.g. this SO question for more info). As soon as you convert the contents of that password field to a String (which is what happens if you use the getText method) the String is placed in the pool, and can be read by others.

If you would look at the implementation of the getPassword method (as can be seen in the SO question @Garbage posted as a comment on your question) you can see this carefully avoids creating a String.

Note that this also means you should not do something like

if ( Arrays.equals( "mySuperSecretPassword".toCharArray(), passwordField.getPassword() ) )

or you still end up with putting the password in the pool, and then you could as easily have used the getText method.

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