Wednesday, May 27, 2009

Masking a password with the Console class

In Java 6 you can use the Console class to mask a password, or more precisely, no characters will be written as output to the console at all when you type the password.
This is achieved with help of the readPassword() method of the Console class. The method returns an array of char, which then easily is passed to the String class constructor to make it useful.
This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.
 
import java.io.Console;
/**
*
* @author
*/
public class Main {
/**
* Example method for entering password from the console
*/
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance, maybe you're running this from within an IDE?");
System.exit(0);
}
console.printf("Testing password%n");
char passwordArray[] = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().passwordExample();
}
}

No comments: