1

I read the following article in Java (why a character array is a better choice than a string for storing password):

1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used :in String pool for re-usability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat.

Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.

2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it.

3) With String there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed. though not a real reason but still make sense.

String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

Output:

String password: Unknown
Character password: [C@110b053

Relating to the above article how it works in .NET, is it the same or something else, what is the in-depth explanation of how String and char work?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3277651
  • 617
  • 6
  • 9
  • 12
    In .NET use [`System.Security.SecureString`](http://msdn.microsoft.com/en-us/library/system.security.securestring%28v=vs.110%29.aspx). – Dour High Arch Feb 20 '14 at 01:34
  • Already covered here: http://stackoverflow.com/questions/141203/when-would-i-need-a-securestring-in-net – Seany84 Feb 20 '14 at 02:09
  • What article? This [2012 blog post](https://javarevisited.blogspot.com/2012/03/why-character-array-is-better-than.html)? (Though there is always the possibility of plagiarism.) – Peter Mortensen Jan 22 '23 at 21:54

1 Answers1

-2

Every language has its reference to which you are able to search for. Here are the two for string and char, for C# and C++, respectively.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131