Why character array is preferred over String for storing Passwords?

In this post, we will see why a character array is preferred over String object for storing highly sensitive information such as user passwords or Social Security numbers (SSNs) in Java.


 

To avoid password being displayed in plain text in thread dump/heap analyzer, during debugging and attacks, we should zero memory containing sensitive information immediately after use instead of waiting for the garbage collection to kick in.

 

Why String should not be used to store passwords?

1. It seems logical and relatively easier to store a password in a String object rather than in a character array. But since String is immutable in Java, we can’t change its contents after usage. That means if we use a String object for storing passwords, we can’t get rid of the password until Garbage collector clears it, which poses a big security threat. So the immutable property of String makes it vulnerable for storing passwords.

 
2. Secondly, there’s always a risk of accidentally printing the password to the application logs.

 

Why character array is preferred over String?

1. A character array should always be used to collect and store sensitive information. Character arrays are mutable data structures, which can be cleared immediately after use and the password won’t have any trace left anywhere in the application, even before the garbage collection. So character array is less vulnerable than a String, even though it only reduces the attack window for the successful hack and doesn’t completely eliminate the risk.

 
2. Also the toString() method of a character array won’t print the contents of the array, its memory address will get printed instead as shown below:

Even this is not secure as password can be still logged in several other ways:

 
So we can conclude that a character array is more secure than the String object even though it also can be exploited. In order to avoid any leaks, we should always encrypt a password rather than storing it in a plain text and clear it from heap as soon as user is authenticated.

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz