Why is char[] preferred over String for passwords?

后端 未结 17 3595
清歌不尽
清歌不尽 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:07

    String is immutable and it goes to the string pool. Once written, it cannot be overwritten.

    char[] is an array which you should overwrite once you used the password and this is how it should be done:

    char[] passw = request.getPassword().toCharArray()
    if (comparePasswords(dbPassword, passw) {
     allowUser = true;
     cleanPassword(passw);
     cleanPassword(dbPassword);
     passw=null;
    }
    
    private static void cleanPassword (char[] pass) {
    
    Arrays.fill(pass, '0');
    }
    

    One scenario where the attacker could use it is a crashdump - when the JVM crashes and generates a memory dump - you will be able to see the password.

    That is not necessarily a malicious external attacker. This could be a support user that has access to the server for monitoring purposes. He could peek into a crashdump and find the passwords.

提交回复
热议问题