0
System.out.print("Enter username: ");
String user = scanner.nextLine();
System.out.print("Enter password: ");
char[] password = console.readPassword();

For Example, I have this code and I was wondering if I am doing this the right way, (Storing input password in char array). Now the real question is how should I compare this char[] password with the username and password in the text file? without converting it into a string.

1 Answers1

0

The reason that console.readPassword() returns a char[] and not a String is because Strings are immutable in Java, and the password will reside in your application's heap memory until it is eventually garbage collected. In the meantime, if a potential attacker gets access to your memory, he/she'll get your password in plaintext.

When password is not converted to a string, after you are done with the password, you can immediately clean it from memory by overwriting on that char[]. For more info on this, see: Why is char[] preferred over String for passwords?

About your code, if you are able to get the password from the file as char[] as well, you can compare the passwords via Arrays.equals(...) method. See the sample code below:

Console console = System.console();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
String user = scanner.nextLine();
System.out.print("Enter password: ");
char[] password = console.readPassword();

String userInTextFile = "user"; // comes from the file
char[] passwordInTextFile = new char[] {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; // comes from the file

if (Objects.equals(user, userInTextFile) && Arrays.equals(passwordInTextFile, password)) {
  System.out.println("Username and password are correct!");
} else {
  System.out.println("Invalid credentials!");
}

Arrays.fill(password, '0'); // clean up the password from the memory
Arrays.fill(passwordInTextFile, '0'); // clean up the passwordInTextFile from the memory

Important Note: Actually, you should not be comparing plaintext passwords at all. You should verify the user-submitted password against the hashed+salted password in the database using a modern password hashing function such as Bcrypt, Scrypt, PBKDF2 etc.

Utku Özdemir
  • 7,390
  • 2
  • 52
  • 49