首页 > 解决方案 > 隐藏用户输入的敏感数据

问题描述

当用户输入敏感数据时,我想在我的 IDE 输出中显示星号 (*)。例如,在控制台输出中我打印“请输入密码:”,然后用户需要输入他的密码。

这是用户输入时的当前终端输出1234

Please enter your password: 1234

这是用户输入时所需的终端输出1234

Please enter your password: ****

标签: java

解决方案


您需要一个单独的线程来屏蔽输入。尝试这个:

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;
   }
}

您可以在https://onlinegdb.com/BkOzy-0LL尝试一下


推荐阅读