Sunday, 17 August 2014

Reading password from command line in Java using java.io.Console

Background

Sometime we need to get passwords from the user. Passwords is a very crucial and secret information. We generally show the text while entering password as '*' characters or not display the characters at all. Java provides in built facility to enter passwords that are not echoed while entering. We are going to see this example.

java.io.console was introduced in Java 6 and has far more convenient methods than plain streams  - System.in and System.out. Also note that this class is Singleton. The Console class provides access to an instance of Reader and PrintWriter using the methods reader() and writer(), respectively

Documentation

We are going to use readPassword() method of Console class is java.io package.

Method documentation is as follows - 

   /**
    * Reads a password or passphrase from the console with echoing disabled
    *
    * @throws IOError
    *         If an I/O error occurs.
    *
    * @return  A character array containing the password or passphrase read
    *          from the console, not including any line-termination characters,
    *          or <tt>null</tt> if an end of stream has been reached.
    */
    public char[] readPassword() {
        return readPassword("");
    }


Code Example


/*
 * author : athakur
 */

public class HelloWorld {
    
    public static void main(String args[]) throws IOException {
        Console console = System.console();
        if(console == null) {
            //This is a bug in eclipse IDE
            //password will be shown on console
            System.out.println("Could not get Console. Falling back to default input mechanism");
            System.out.println("Enter password : ");

            String password = new BufferedReader(new InputStreamReader(System.in)).readLine();

            System.out.println("Password : " + password); 

            //process password

        }

        else {

            //intended behavior
            System.out.println("Enter password : ");

            char[] password = console.readPassword();

             System.out.println("Password : " + Arrays.toString(password)); 

            //process password

        }

    }

}

Generally we would store the password in DB or validate. In above code I am printing it just to demonstrate it's working. Note how the password is not printed when user types it in.



When will it fail?

You must have notices the null check in the beginning of the code. That is because there is a know bug (bug #122429) in Eclipse IDE. We cannot get Console instance. So we have added a null check. However the mechanism will work just fine in normal console.




Related Links

t> UA-39527780-1 back to top