JAVA: Why you should use char[] instead of String for passwords

Whenever you are designing a backend with JAVA or any other language with a garbage collector and you need to store passwords or other sensitive information temporarily, you should always use a character array (char[]) instead of String. Why you ask?

Why not Strings?

Strings are immutable. Whatever data you store in a String data type, remains there until the garbage collector cleans it up (or you have to use reflection). And in this duration, if any attacker gets access to your JVM, he/she can easily read your password.

Why Character Array?

Arrays are mutable. It means after you are done with the array, you can overwrite each character and clear your sensitive information from the system without having to wait for the garbage collector. This reduces the window of opportunity for the attacker.

No accidental reveal

If you use a character array, it also removes the possibility of accidental printing of sensitive information to log files or console. This is because you can’t print a character array directly. You have to iterate and print each character. While in the case of a String, it is printed directly.


this will print –

String: MyPassword
Array: [C@4152637e

So next time you design a backend with JAVA or any other language with a garbage collector, keep this in mind.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Powered by

Up ↑

%d bloggers like this: