I want to make a Java program that reads a Password from STDIN silently. I mean, without outputting any pressed chars to the terminal and keeping it hidden from commandline
This is more compatible and less secure, it should work with your virtual console in your IDE, for background processes that don't have a TTY, and normal consoles. When a console is not found, it falls back to use a BufferedReader which will expose the password to screen as the user types it in some cases.
Java Code:
import java.io.*;
public class Runner {
public static void main(String[] args) {
String username = "Eric";
try {
ReadMyPassword r = new ReadMyPassword();
char[] password = r.readPassword(
"Hey %s, enter password to arm the nuclear wessels>", username);
System.out.println("Exposing the password now: '" +
new String(password) + "'");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ReadMyPassword{
public char[] readPassword(String format, Object... args)
throws IOException {
if (System.console() != null)
return System.console().readPassword(format, args);
return this.readLine(format, args).toCharArray();
}
private String readLine(String format, Object... args) throws IOException {
if (System.console() != null) {
return System.console().readLine(format, args);
}
System.out.print(String.format(format, args));
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
return reader.readLine();
}
}
Here's what it looks like through through the Eclipse virtual console:
Hey Eric, enter password to arm the nuclear wessels>12345
Exposing the password now: '12345'
Program Sisko 197 ready for implementation on your command
Here's what it looks like through the normal console.
el@apollo:/home/el/bin$ java Runner
Hey Eric, enter password to arm the nuclear wessels>
Exposing the password now: 'abcdefg'
Program Sisko 197 ready for implementation on your command
el@apollo:/home/el/bin$