简体   繁体   English

屏蔽Java中的密码字段

[英]Masking the password field in java

I am developing a Java command line application and I need to display an asterisk (*), or any similar sign, when the user inputs the password. 我正在开发Java命令行应用程序,当用户输入密码时,我需要显示一个星号(*)或任何类似的符号。 I have tried using the replace() method but it accepts only one character. 我尝试使用replace()方法,但它仅接受一个字符。 Is there a way to pass all the letters and numbers as an argument for this replace method. 有没有一种方法可以将所有字母和数字作为此replace方法的参数传递。 Or else what is the method of masking the suer input. 否则,掩盖suer输入的方法是什么。

I cannot use the console.readPassword technique here, because I need the password (tpyed by the user) in the String data type. 我不能在这里使用console.readPassword技术,因为我需要String数据类型中的密码(由用户输入)。

Actually, you cannot use the replace method. 实际上,您不能使用replace方法。 By using it, the user input is still visible, and you're only changing the value you stored into memory. 通过使用它,用户输入仍然可见,而您只需要更改存储在内存中的值即可。

If you need the password as a String (that's not recommended for security reasons, but anyway...): 如果您需要密码作为字符串(出于安全原因不建议这样做,但是无论如何...):

char[] pwd = console.readPassword();
String str = new String(pwd);

Just convert the char array to a string. 只需将char数组转换为字符串即可。 Console.readPassword is exactly made for your use case (reading a pwd :D). Console.readPassword完全适合您的用例(读取pwd:D)。

Originally, it's char[] and not String because you can null the content of the array and your password is gone while String may gets pooled and stay in your memory. 最初,它是char []而不是String,因为您可以使数组的内容为空,并且密码可能丢失,而String可能会被合并并保留在您的内存中。

这里有一个示例: Java编程语言 [java.sun.com] 中的密码屏蔽

只需使用console.readPassword() ,然后从char[]创建一个String

String passWord = new String(chars);

Since you want to output asterisks, you cannot use console.readPassword. 由于要输出星号,因此不能使用console.readPassword。 Instead, you have to do it on your own: disable the echoing, switch the input to unbuffered (char-wise instead of line-wise) mode, read the password char by char, print an asterisk for each char you read. 取而代之的是,您必须自己做:禁用回显,将输入切换为非缓冲(按字符而不是按行)模式,逐个字符读取密码char,为每个读取的char打印一个星号。 I propose you look for a curses-like library for java (there are several around, see What's a good Java, curses-like, library for terminal applications? , for this task. 我建议您为Java寻找一个类似curses的库(有很多方法,请参见针对此终端应用程序有什么类似curses的Java库?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM