gpt4 book ai didi

java - 隐藏用户输入的敏感数据

转载 作者:行者123 更新时间:2023-12-01 17:43:08 24 4
gpt4 key购买 nike

当用户输入敏感数据时,我想在 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;
}
}

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

关于java - 隐藏用户输入的敏感数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60912909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com