Typefully

Java: Is "char[]" Better Than "String" to Store Password

Avatar

Share

 • 

4 years ago

 • 

View on X

Java: Is "char[]" Better Than "String" to Store Password a thread...
This question is very popular in Java Interviews, and a good understanding is required to perform well in the interviews. Let's try to understand this topic in-depth.
There're a few reasons why using char[] is safe for storing passwords in Java: 1. String Immutability Issue 2. Java's Own Recommendation 3. Accidental Password Logging
1. String Immutability Issue: Strings are Immutable and stored in a String pool. After its use, it still remains in the pool and it does not get garbage collected for a long time.
And someone with access to a memory dump may access sensitive info stored in it and it poses a security threat. In the case of a char array, we can reassign its value to null and make the previous value eligible for GC.
Still, before GC someone can also access char[] values but as compared to String it reduces the window for an attacker. Hence it's comparatively more secured than String but not fully.
2. Java's Own Recommendation: In Swing, Java itself uses the getPassword() method of JPasswordField class which returns a char[]. It doesn't use the deprecated getText() method which returns passwords in the clear text due to security reasons.
3. Accidental Password Logging: There's always a risk of printing String as plain text in a log file or console. But contents of an array will not get printed, but instead, its memory location gets printed.
(Opinion) How much practical is it to access dump and read passwords? In my opinion, this question is more interview centric rather than a real-life problem.
Because normally memory dumps are accessible between admin-level users. Until they try to sniff into the dump it's difficult to know the password.
Or If suppose some attacker gains access to our servers as admin then there are tons of other things at risk not only dumps. The probability is small for such type of attack but yes it's still a risk. So better stick to the best practice.
Conclusion: Implement a proper code reviewing process to regularly check if any sensitive info is printed in logs which can be avoided? Try to use char[] to store passwords and after we finish using it we can wipe the data immediately.
Thanks for Reading! Do you like reading such a detailed thread on Java? Then you might also like reading my previous Java thread: twitter.com/vikasrajputin/status/1512404438920564752
Namaste, I'm Vikas! I write a thread every Mon, Wed & Fri on Java, Javascript & Fullstack Development. To read all my future threads follow @vikasrajputin Any Query, Feedback & Suggestions? Put them in the comments below. See you in the comments :)
Avatar

Vikas Rajput

@vikasrajputin

Sr. Backend Engineer. Simplifying Backend and sharing what I learn along the way. Building Gujarat's biggest java community at @juggujarat