Why is char[] preferred over String for passwords?

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

    The short and straightforward answer would be because char[] is mutable while String objects are not.

    Strings in Java are immutable objects. That is why they can't be modified once created, and therefore the only way for their contents to be removed from memory is to have them garbage collected. It will be only then when the memory freed by the object can be overwritten, and the data will be gone.

    Now garbage collection in Java doesn't happen at any guaranteed interval. The String can thus persist in memory for a long time, and if a process crashes during this time, the contents of the string may end up in a memory dump or some log.

    With a character array, you can read the password, finish working with it as soon as you can, and then immediately change the contents.

提交回复
热议问题