Friday, February 06, 2009

Password Prompt In Java Console Application

The most wanted feature in Java has been finally made available - console based application to process password entry without echoing on console. If you were a C/C++ programmer, you might have used getch() to read password from console without revealing what the user is typing on the console.

This enhancement request was tracked from 1.1 release of Java and now resolved in 1.6 release. The implementation is to get an access to Console and then use appropriate methods. A quick code snippet:
char[] password=System.console().readPassword("Enter password:", new Object[0]);

Console instance has to be obtained from System through console() method, not like System.in or System.out instance variable. This is because, the host application may have cases that there is no supported console available and the method would return null. Hence the above code should be actually written as:
Console console=System.console();
if (null!=console){
password=console.readPassword("Enter password:", new Object[0]);
}else{
throw IOException("No console available");
}

Why char[] is returned? Garbage collection won't clear the content of freed memory. If it is an array of character, the values are in memory and hence can be overwritten after use.
//after use
java.util.Arrays.fill(password, ' ');

What is the need for the arguments? It is just to ease the use of this function through these parameters. First argument is a format string which can have format specifiers like %s, %d and so on. The second argument is the data for those place holders specified in format string.
Object[] params=new Object[2]; //we will be using 2 variable data while prompting
params[0]=5; //auto boxing
params[1]="th attempt,";
console.readPassword("[%04d %s] password please:", params);

For simple use, there is an overloaded method with no argument:
console.readPassword();

Other usability features:
console.readLine(); //no need to construct many io classes to do a plain readLine.
console.printf(format, params); //same as c printf
console.flush(); //flush the output buffer to be printed immediately

No more waiting, start using this feature...