How to use Scanner to read silently from STDIN in Java?

前端 未结 4 751
终归单人心
终归单人心 2020-12-03 14:43

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

4条回答
  •  再見小時候
    2020-12-03 15:22

    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:

    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$
    

提交回复
热议问题