Java – Why does JPasswordField.getPassword() create a String with the password in it

javapasswordsSecurityswing

Swing's JPasswordField has the getPassword() method that returns a char array. My understanding of this is that the array can be zeroed immediately after use so that you do not have sensitive things hanging around in memory for long. The old way to retrieve the password was to use getText(), which returns a String object, but it has been deprecated.

So, my question is why it is actually being used by Java during the retrieval process using getPassword()??? To be clearer, I was debugging my test app for something else**, I followed the calls and bang… getText() in JPasswordField was called and, of course, a nice String object with my password has been created and now is hanging around the memory.

Try it for yourself:

public class PasswordTest() {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPasswordField passField = new JPasswordField();
        pass.addActionListener(new ActionListener() {
            public ActionPerformed(ActionEvent evt) {
                char[] p = passField.getPassword(); // put breakpoint
                // do something with the array
            }
        });
        frame.add(passField);
        frame.setVisible(true);
        frame.pack();
    }
}

Follow up question: is this 'hidden' use of getText() dangerous in any way? Of course a dedicated attacker WILL get your password if it has compromised the system, I am talking about a less dedicated one 😉

**I came across this while I was looking for a way to actually display some sensitive data on a Swing component without using a String object. Apparently there is no way to do it unless I am willing to rewrite part (all?) of the Swing API.. not gonna happen.

Best Answer

This works for me and helps you to build a Stringified password:

String passText = new String(passField.getPassword());