Thursday, 2 October 2014

How To Read Passwords From Console Without Echoing in Java


    When ever you want to install a package / software from terminal in Linux based machines, you have to enter super user's password. If you observe, while entering your password, you can't see what you are typing. Here the terminal is not echoing what you have entered. You can do the same in java also, using Console class.

The Console class is intended for reading directly from a program's controlling terminal. When you run an application from a "terminal window" or "command prompt window" on most systems, its console and its standard input are both connected to the terminal, by default.

You cannot create an object of Console yourself. For this, call System.console() method,which gives a Console Object, then you can call methods such as readLine(), which behaves same as method readLine() from BuferredReader class.
 
import java.io.Console;

public class ConsoleReadLine {
 
     public static void main(String[] args) {
 Console console = System.console();
 String name = console.readLine("Please enter user name \n");
 System.out.println("Hello " + name.toUpperCase());
     }
}
The System.console() method can return null if the console isn't connected. Annoyingly, some IDEs including Eclipse don't manage to set up a controlling terminal when you use the Run As -> Java Application mechanism. So while writing production code, you should always check for null before trying to use the console.

Reading Password Without Echoing :

     Reading password without having it echo, is the standard facility of command line applications for decades. If you want to provide this feature in java, use readPassword() method of Console class. This method returns an array of bytes, which can be used directly in some encryption and security APIs, or can be easily converted into a String.

It is generally advised to overwrite the byte array after use to prevent security leaks when other code can access the stack.
Program
import java.io.Console;
import java.util.Arrays;

public class ConsoleRead {
 
    public static void main(String[] args) {
 Console console = System.console();  
 if(console != null) {
     char[] password = null;
     try {   
  password = console.readPassword("Please enter Password");
  System.out.println("Password is " + new String(password));
     } finally {
        if(password != null) {
   Arrays.fill(password, ' ');
        }
    }
 } else {
  throw new RuntimeException("No console, can't get password");
 }  
    }
}
Output : 
 When i ran this program from eclipse, i got null pointer exception, because the console is not connected to the console of Eclipse window, resulting console object to be null.The above output is when i ran the code from command prompt.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.