0

I want to show star characters (*) in my IDE output when a user is entering sensitive data. For example, in the console output I print "Please enter password: " and then the user needs to enter his password.

This is the current terminal output when a user enters 1234:

Please enter your password: 1234

Here is the desired terminal output when a user enters 1234:

Please enter your password: ****
Brian Kelly
  • 5,564
  • 4
  • 27
  • 31

1 Answers1

0

You need a separate thread to mask input. try this:

import java.io.*;

public class Test {
    public static void main(final String[] args) {
        String password = PasswordField.readPassword("Enter password:");
        System.out.println("Password entered was:" + password);
    }
}


class PasswordField {

   public static String readPassword (String prompt) {
      EraserThread et = new EraserThread(prompt);
      Thread mask = new Thread(et);
      mask.start();

      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String password = "";

      try {
          password = in.readLine();
      } catch (IOException ioe) {
          ioe.printStackTrace();
      }
      et.stopMasking();
      return password;
   }
}   

class EraserThread implements Runnable {
   private boolean stop;

   public EraserThread(String prompt) {
       System.out.print(prompt);
   }

   public void run () {
      while (!stop){
         System.out.print("\010*");
         try {
            Thread.currentThread().sleep(1);
         } catch(InterruptedException ie) {
            ie.printStackTrace();
         }
      }
   }

   public void stopMasking() {
      this.stop = true;
   }
}

You can try it at https://onlinegdb.com/BkOzy-0LL

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48