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

前端 未结 7 2028
长发绾君心
长发绾君心 2020-11-28 10:52

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

相关标签:
7条回答
  • 2020-11-28 11:57

    Actually, here's the Sun implementation of getPassword():

    public char[] getPassword() {
        Document doc = getDocument();
        Segment txt = new Segment();
        try {
            doc.getText(0, doc.getLength(), txt); // use the non-String API
        } catch (BadLocationException e) {
            return null;
        }
        char[] retValue = new char[txt.count];
        System.arraycopy(txt.array, txt.offset, retValue, 0, txt.count);
        return retValue;
    }
    

    The only getText in there is a call to getText(int offset, int length, Segment txt), which calls getChars(int where, int len, Segment txt), which in turn copies characters directly into the Segment's buffer. There are no Strings being created there.

    Then, the Segment's buffer is copied into the return value and zeroed out before the method returns.

    In other words: There is no extra copy of the password hanging around anywhere. It's perfectly safe as long as you use it as directed.

    0 讨论(0)
提交回复
热议问题