Why do I use char[] instead of string when I use password?

Asked 2 years ago, Updated 2 years ago, 194 views

When you say "getText()" in "Swing", the return value is "String" If you look at the return value of the password field getPassword, it's char[].

If you look at that, String has security issues or uses it more than char[] I think it's because it's uncomfortable, is there an exact reason?

string security java passwords char

2022-09-22 22:38

1 Answers

Security reasons are the biggest. String is a constant, which means that once it is created and memory dumps, there is no way to erase the data until the garbage collector clears it.

When it is an array, you can initialize it once and erase or change the data at any time. If you overwrite the data in the array, the password is nowhere to be found.

That's why we use char [] to prevent certain strikers.

To put it simply

    public static void main(String[] args) {
        Object pw = "Password";
        System.out.println("String: " + pw);

        pw = "Password".toCharArray();
        System.out.println("Array: " + pw);
    }

If you accidentally expose the password in these codes, the string is immediately output, but char[] is relatively safe.

    String: Password
    Array: [C@5829428e


2022-09-22 22:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.