Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Char array is better than String for password prevention

    • 0
    • 1
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 522
    Comment on it

    Why Char array is better than String for storing secure data like Password in Java?

    As we know that String is immutable in Java if we store password as String, it will be available in memory (Heap) until Garbage collector clears it and since String are used in String pool for re-usability. So there is high chance that it will be remaining in memory for long duration, which poses a security threat. If anyone who has access to memory dump can find the password in clear text thats the reason user always used an encrypted password than plain text.

    If we do any changes in String content then it will create a new String object in heap instead of changing existing password because of immutable property. While if you use char [] you can set all his elements with other values. So storing password in char [] array clearly mitigates security risk of stealing password.

    With String there is always a risk of printing plain text in log file or console but if use Array you wont print contents of array instead its memory location get printed.

    Lets take an example here for you

    public class PasswordTest {
            public static void main(String[] args)
                String strPassword = "Kailkhuri";
                char[] charPassword = new char[]{'K','a','i','l','k','h','u','r','i'};
                System.out.println("String password: " + strPassword);
                System.out.println("Character password: " + charPassword);


    String password: Unknown

    Character password: [C@110b053

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: