Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
268 Members
Join this group to post and comment.
Archana Priyadarshini
Archana Priyadarshini
Computer Science
26 Jan 2019

Why is a char array( char[] )preferred over String to store a password?

String is immutable in Java.It is stored in the String pool. Once it is created it stays in the pool until garbage collected. This has greater risk of 

  1. someone producing a memory dump to find the password 
  2. The application inadvertently logging password as a readable string.

If you use a char[] instead, you can override it with some dummy values once done with it.With an array, you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.

AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
3mos ago

We use character array over a string for storing the password in java is due to the following reasons:

1.Strings are immutable:Strings are immutable in java and therefore if a password is stored as a plain text it will be available in memory until garbage collector clears it and as strings are used in string pool for re Usability there are high chances that it will remain in memory for longer duration,which is a security threat.Strimgs are immutable and there is no way that the contents of strings can be changed because any String will produce new string.

2.Security:Anyone who has access to memory dump can find the password in clear text and that is another reason to use encrypted password than the plain text.So storing password in character array clearly mitigates security risk of stealing password.

3.Log file safety:With an array,one can explicitly wipe the data,overwrite the array and password won't be present anywhere in the system.

With plain string there are much higher chances of accidentally printing the password to logs,monitors or some other insecure place.Character array is less vulnerable