Why is char[] preferred over String for passwords?

后端 未结 17 3592
清歌不尽
清歌不尽 2020-11-21 04:34

In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String)

17条回答
  •  野的像风
    2020-11-21 05:04

    While other suggestions here seem valid, there is one other good reason. With plain String you have much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.

    Consider this:

    public static void main(String[] args) {
        Object pw = "Password";
        System.out.println("String: " + pw);
    
        pw = "Password".toCharArray();
        System.out.println("Array: " + pw);
    }
    

    Prints:

    String: Password
    Array: [C@5829428e
    

提交回复
热议问题