Why is char[] preferred over String for storing passwords?
sobes.tech AI
Answer from AI
String objects are immutable. This means that once a string is created, its contents cannot be changed. If you store a password in a String, it will remain in memory until the garbage collector removes this object. During this time, an attacker could access the memory and read the password.
char[] arrays can be modified. After using a password stored in a char[], you can explicitly overwrite the array elements, for example, with null characters. This ensures that the password is removed from memory as soon as it is no longer needed, significantly reducing the risk of leakage.
Additionally, working with strings carries the risk of creating additional copies in the string pool, which also increases the time the password remains in memory.
// Example of storing a password in a char[] and clearing it
char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
// Using the password (e.g., for authentication)
// ...
// Clearing the array after use
java.util.Arrays.fill(password, ' ');
// The password is now removed from memory