Selecting Password row and Pasting in notepad reveals the password

后端 未结 4 2050
暗喜
暗喜 2020-12-20 09:05

I have been facing the above mentioned problem in my java application that I recently created. Even though I clearly set the field as JPasswordField and have tried to mask t

4条回答
  •  眼角桃花
    2020-12-20 09:32

    Playing guessing games as everybody else (the description is ... lacking ;-)

    So assuming a two-column tableModel containing username and password, respectively, rendered in a JTable with drag-enabled to true and default transferHandler. Assuming the rendering of the password in the JTable is "masked" somehow but appears as clear-text in c&p.

    @Robin already detected the underlying reason: the default transferHandler simply uses getValueAt(...).toString() to create the transferable. Which leads to revealing the password string, it that's what is stored in the model.

    A simple way out (as opposed to a better Transferhandler, which again @Robin already mentioned: uses the rendered value instead of the toString. Note to myself: file task for SwingX) for is to not store the plain password but a wrapper object:

    public class Password {
        private final String password;
    
        public Password(String password) {
           this.password = password;
        }
    
        // api as needed to make it worthwile ...
    
        public boolean isValid(String password) {
            ...
        }
    
        // for the sake of c&p, override the toString
        // for the lazy, this is the string rep used by the default renderer
        @Override
        public String toString() {
            return "******************";
        }
    }
    

    Addendum (this is SwingX specific, extending my comment to @Robin's example)

    Actually I like the approach as a quick solution for copying. Just "fixing" the wrapping model to make full use of current api, that is to use table.getStringAt(...) for the String representation. With that, there is no need to pass the StringValue at several places, internals will handle it as appropriate.

    private static class StringTableModel extends AbstractTableModel {
        private JXTable delegateTable;
    
        private StringTableModel(JXTable aTable) {
            delegateTable = aTable;
        }
    
        @Override
        public int getRowCount() {
            return delegateTable.getRowCount();
        }
    
        @Override
        public int getColumnCount() {
            return delegateTable.getColumnCount();
        }
    
        @Override
        public Object getValueAt(int aRowIndex, int aColumnIndex) {
            return delegateTable.getStringAt(aRowIndex, aColumnIndex);
        }
    }
    

    On the framework level, SwingX should support WYSIWYE (What-you-see-is-what-you-export) out off the box, just as its other WYSIWYX: X = M for match, X = S for sort, X = F for filter. Raised issue 1477 in the SwingX issue tracker

提交回复
热议问题