在java中屏蔽密码字段
我正在开发一个 Java 命令行应用程序,当用户输入密码时,我需要显示星号 (*) 或任何类似的符号。我尝试过使用replace()方法,但它只接受一个字符。有没有办法将所有字母和数字作为此替换方法的参数传递。或者说屏蔽suer输入的方法是什么。
我不能在这里使用 console.readPassword 技术,因为我需要字符串数据类型的密码(由用户输入)。
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. I have tried using the replace() method but it accepts only one character. Is there a way to pass all the letters and numbers as an argument for this replace method. Or else what is the method of masking the suer input.
I cannot use the console.readPassword technique here, because I need the password (tpyed by the user) in the String data type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
实际上,你不能使用replace方法。通过使用它,用户输入仍然可见,并且您只是更改存储到内存中的值。
如果您需要字符串形式的密码(出于安全原因不建议这样做,但无论如何......):
Actually, you cannot use the replace method. 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 数组转换为字符串即可。 Console.readPassword 完全适合您的用例(读取密码:D)。
最初,它是 char[] 而不是 String,因为您可以将数组的内容清空,您的密码就会消失,而 String 可能会被池化并保留在您的内存中。
Just convert the char array to a string. Console.readPassword is exactly made for your use case (reading a 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.
这里有一个例子:
Java 编程语言中的密码屏蔽[java.sun.com]
There is an example here:
Password Masking in the Java Programming Language[java.sun.com]
只需使用console.readPassword(),然后从
char[]
创建一个String
:Just use
console.readPassword()
and then make aString
from thechar[]
:由于要输出星号,因此不能使用console.readPassword。相反,您必须自己执行此操作:禁用回显,将输入切换为无缓冲(按字符而不是按行)模式,逐个字符读取密码,为您读取的每个字符打印一个星号。我建议你寻找一个类似curses的java库(有几个,请参阅对于此任务来说,对于终端应用程序来说,什么是一个好的 Java 类curses 库?。
Since you want to output asterisks, you cannot use 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. 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.