Prompt for password from the consoleTag(s): Security
A separate thread is used to send to the console the backspace character to erase the last-typed character.
import java.io.*;
import java.awt.*;
public class PwdConsole {
public static void main(String[] args) throws Exception {
ConsoleEraser consoleEraser = new ConsoleEraser();
System.out.print("Password? ");
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
consoleEraser.start();
String pass = stdin.readLine();
consoleEraser.halt();
System.out.print("\b");
System.out.println("Password: '" + pass + "'");
}
}
class ConsoleEraser extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print("\b ");
}
}
public synchronized void halt() {
running = false;
}
}Java SE6 provides a buiilt-in mechanism to input a password from the console.
java.io.Console cons;
char[] passwd;
if ((cons = System.console()) != null &&
(passwd = cons.readPassword("[%s]", "Password:")) != null) {
...
}
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com