Why is char[] preferred over String for passwords in programming?

Technology CommunityCategory: StringsWhy is char[] preferred over String for passwords in programming?
VietMX Staff asked 3 years ago

Strings are immutable i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. Simply speaking here’s no way (aside from reflection) you can get rid of the data before garbage collection kicks in.

With an array, you can explicitly wipe the data after you’re done with it. You can overwrite the array with anything you like, and the password won’t be present anywhere in the system, even before garbage collection.

Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use.