java - 隐藏用户输入的敏感数据
问题描述
当用户输入敏感数据时,我想在我的 IDE 输出中显示星号 (*)。例如,在控制台输出中我打印“请输入密码:”,然后用户需要输入他的密码。
这是用户输入时的当前终端输出1234
:
Please enter your password: 1234
这是用户输入时所需的终端输出1234
:
Please enter your password: ****
解决方案
您需要一个单独的线程来屏蔽输入。尝试这个:
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;
}
}
推荐阅读
- flutter - 在flutter中使用getX打开页面时自动调整页面的语言
- histogram - 使用 Prometheus 跟踪两个请求之间的时间
- python - 加入和分组 2 个数据帧
- wordpress - 为什么使用修改后的 $price 调用 woocommerce_variation_prices_price 过滤器时,将 sale_price 设置为等于 regular_price?
- node.js - Fastify 应用在 Cloud Run 上部署时返回 400
- excel - VBA删除工作表名称包含文本的所有工作表中的列
- javascript - 异步/等待后如何记录返回值?
- python - 如何打印等间距的数据?
- maven - 我们如何减少从 maven-assembly-plugin 生成的 jar 文件大小?只有 2 个依赖项,我的 jar 文件大小为 91 mb
- c# - 从 vb.net 中的网格视图中查找单元格值,前端 asp.net