November 27, 2013

Published November 27, 2013 by

Read password (hidden) from Console


Generally all the texts given as input in a Java console application are visible. When we read a password from a Java console application, it will not be wise to display the input password. If we want to hide the password, we can use the readPassword method java.io.Console class to read password. This class is available since version 1.6.

Console class is used to access the character-based console device, if any, associated with the current Java virtual machine. If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method. If no console device is available then an invocation of that method will return null.

An example below:
import java.io.Console;

public class ConsolePassword {

    public static void main(String[] args) {
        String username;
        char[] password;

        Console console = System.console();

        if (console != null) {
            System.out.print("Username: ");
            username = console.readLine();

            System.out.print("Password: ");
            password = console.readPassword();

            if (username.equalsIgnoreCase("admin")) {
                if (String.valueOf(password).equals("myPassword")) {
                    System.out.println("Username and password are correct");
                } else {
                    System.err.println("Wrong password");
                }
            } else {
                System.err.println("Wrong username");
            }

        } else {
            System.err.println("No console device is available");
        }
    }

}
You should press the “Enter” key when the password input is finished. The input password will not be shown and it will not show any progress as well.

Output of this code: