Monday, August 14, 2017

Why Char array is preferred over String to store password

String is immutable in java and stored in a separate pool called String pool pool of interned String. Once it's created it stays in the pool until unless it is garbage collected.
So even though we are done with password it's available in memory for longer duration and there is no way to avoid it. It's a security risk because anyone having access to memory dump can find the password as clear text.
If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it's available in memory that avoids the security threat with String.

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]

No comments:

Post a Comment