1

I want to prompt the user for a password in a Java code, and I'd rather not have the input printed to the screen for security reasons.

I am aware of the class Console, but I would like to be able to run my program from an IDE for testing reasons. Any alternatives?

user2891462
  • 3,033
  • 2
  • 32
  • 60
  • 2
    The only solution I can find is to use Console, but fall back to a regular reader if there is no Console. It was suggested here: http://stackoverflow.com/a/20982591/1041364 – Andrew Stubbs Jul 24 '14 at 12:56

1 Answers1

1

I would strongly recommend using a set up where Console is used when possible, falling back to a Scanner or Reader when it is not.

However, there is a very ugly solution to the specific wording of this question, which I found here.

The solution is basically to repeatedly send the backspace (\b) character to the console to hide whatever gets written. It's may be possible for you to formulate a more resource friendly version with some kind of listener, but I'm not sure about that.

Some example code that should do exactly this:

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;
        }
    }
}
Andrew Stubbs
  • 4,322
  • 3
  • 29
  • 48
  • Effective and very ugly indeed. Since there is apparently no prettier solution I will use it for the moment until I think of other possible changes in my code. Thanks :) – user2891462 Jul 24 '14 at 16:22