![]()
I need to read passwords from the command line. Is there a way to easily read characters from the command line securely in
Java? Specifically, how do you echo * to the command line?
I've seen that question many times. Unfortunately, there does not appear to be a way to securely accept passwords on the command
line from within a Java program by simply using the supplied Java APIs. Let's look at why that is the case.
To read items in from the command line, we use the input stream System.in. If we dig into the code a bit, we see that the default System.in input stream is really just an InputStream. Digging into my implementation of Java (IBM 1.1.7), the true implementation type of that System.in is a FileInputStream. That input stream is set to read in from the source file descriptor FileDescriptor.in. However, FileDescriptor.in is initialized by natively defined code. It is left to the system to point the FileDescriptor.in at the standard input handle.
If we look at the API definition for FileInputStream, we see that the read method is natively defined. Typed data is not taken from the command line and made available from the
standard in file descriptor until the return button is pressed. Since we cannot grab a character as it is typed, there is
no way to intercept the character and echo a * to the command line. Instead, we can only grab complete lines.
That leaves us with few alternatives. Unfortunately, most of the solutions require us to dive into native code or employ a GUI frontend. Briefly, here are a few solutions:
FileInputStream and provide your own read() implementation.
javaBy Anonymous on August 12, 2009, 6:50 amreading password
Reply | Read entire comment
View all comments