Monday, March 25, 2013

Why is char[] preferred over String for passwords?


1) 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 Strings 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
2) Java recommendation using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason.
3) toString() 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.
String strPwd="Java1234";
char[] charPwd= new char[]{'J','a','v','a','1','2','3','4'};
System.out.println("String password: " + strPwd);
System.out.println("Character password: " + charPwd);
String password: Unknown Character password: [C@52c8c6d9
Final thoughts: Though using char[] is not just enough you need to erase content to be more secure. I also suggest working with hash'd or encrypted password instead of plaintext and clearing it from memory as soon as authentication is completed.