Any reason to prefer to store the password in Char array over String
As we know String is a class. It's immutable as per the wrapper class in java. String follows the pool concept. Now we provide some deep understanding to find out the reason why we prefer char[] array to store the password over the String.
It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String 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. This feature makes objects unsuitable for storing security-sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.
Strings are immutable. That means once you've created the if another process can dump memory, there'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.
So yes, this is a security concern - but even using char[]
only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.
As noted in the comments, arrays being moved by the garbage collector may leave stray copies of the data in memory. I believe this is implementation-specific - the garbage collector may clear all memory as it goes, to avoid this sort of thing. Even if it does, there's still the time during which the char[]
contains the actual characters as an attack window.
post a comment