Monday 16 June 2014

Why character array is preffered to store Password than String?

        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 reusability 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.

        With Strings there is always a risk of printing plain text in a log file or console  but if use Array you won't print contents of the array instead its memory location get printed, though not a real reason but make but still make sense.
      For Example,
                            class PassCharArrEx {
                                   public static void main(String args[]) {
                                           String pass = "password_of_blog";
                                           char chpass[] = "password_of_blog".toCharArray();
Output :

No comments:

Post a Comment