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.