Why is char[] preferred over String for passwords?

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

    These are all the reasons, one should choose a char[] array instead of String for a password.

    1. Since Strings are immutable in Java, if you store the password as plain text it will be available in memory until the Garbage collector clears it, and since String is used in the String pool for reusability there is a pretty high chance that it will remain in memory for a long duration, which poses a security threat.

    Since anyone who has access to the memory dump can find the password in clear text, that's another reason you should always use an encrypted password rather than plain text. Since Strings are immutable there is no way the contents of Strings can be changed because any change will produce a new String, while if you use a char[] you can still set all the elements as blank or zero. So storing a password in a character array clearly mitigates the security risk of stealing a password.

    2. Java itself recommends using the getPassword() method of JPasswordField which returns a char[], instead of the deprecated getText() method which returns passwords in clear text stating security reasons. It's good to follow advice from the Java team and adhere to standards rather than going against them.

    3. With String there is always a risk of printing plain text in a log file or console but if you use an Array you won't print contents of an array, but instead its memory location gets printed. Though not a real reason, it still makes sense.

    String strPassword="Unknown";
    char[] charPassword= new char[]{'U','n','k','w','o','n'};
    System.out.println("String password: " + strPassword);
    System.out.println("Character password: " + charPassword);
    
    String password: Unknown
    Character password: [C@110b053
    

    Referenced from this blog. I hope this helps.

提交回复
热议问题