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 history and the operating system processlist ps
.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The class java.io.Console may be useful:
This reads a sequence of chars from the console, without echoing anything. Note that it only works when you launch your java application with a real console. Otherwise, System.console() returns null.
You might want to give java.io.Console a look
It has a readPassword method which "Reads a password or passphrase from the console with echoing disabled".
Most secure option for Java to get a password with STDIN:
This demonstration is with Java on an Ubuntu 12.10 terminal. Grabbing the password with STDIN is a good idea security wise, since the password is not exposed to command line history or within the processlist with
ps
. The password letters typed are thrown away and not stored.Java Code:
Conditions if you use the above code
If super high security is your top priority don't even store that password in a
String
. Encrypt it immediately after receiving it from the user. That way if some clever person scans the memory of your program, they won't find your plaintext password there.If you try to run this program through a background job scheduler, then it is possible that
System.console().readPassword()
will return a NullPointerException which is a feature to enhance security. It denies access to shenanigans like virtual consoles and background tasks. If you want it to work right with virtual consoles see my other answer on this page.If you try to run this code through an IDE like Eclipse, Netbeans or any other virtual console, then
System.console().readPassword()
will throw a NullPointerException because no real console is found, and the program will halt. This is a feature, not a bug.What is looks like on the console:
A less secure option to get the password via STDIN that works with background jobs, virtual consoles, and normal consoles:
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:
Here's what it looks like through through the Eclipse virtual console:
Here's what it looks like through the normal console.