java 字符串到星号,屏蔽密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7687600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String to asterisk, masking password
提问by Michael
I'm creating this simple login code for an ATM machine. You enter username and password and you logs in, that works just great. Since I'm not connecting to a database or an external text file and I've just got 1 user, it's just written plainly in the Java code. But when you enter the password "p4ss" I want it to be masked, so instead of seing it on the screen while typing you should see "* * * *" or " " just blank (Like when you enter pass on Linux).
我正在为 ATM 机创建这个简单的登录代码。您输入用户名和密码并登录,效果很好。因为我没有连接到数据库或外部文本文件,而且我只有 1 个用户,所以它只是用 Java 代码简单地编写了。但是当你输入密码“p4ss”时,我希望它被屏蔽,所以不要在输入时在屏幕上看到它,你应该看到“* * * *”或“”只是空白(就像你在Linux上输入pass一样)。
Currently my code looks like this:
目前我的代码是这样的:
String user;
String pass;
System.out.print("User: ");
user = Keyboard.readString();
System.out.print("Pass: ");
pass = Keyboard.readString();
if ((user.equals("Admin")) && (pass.equals("p4ss")))
{
menu();
}
else
{
out.println("Wrong username or password.");
}
Would appreciate any help I could get.
我会很感激我能得到的任何帮助。
回答by Pieter
Michael, have a look at the description on Sun's website: https://web.archive.org/web/20120214061606/http://java.sun.com/developer/technicalArticles/Security/pwordmask
迈克尔,看看 Sun 网站上的描述:https: //web.archive.org/web/20120214061606/http: //java.sun.com/developer/technicalArticles/Security/pwordmask
Or, if you're using Java 5 or newer, you can use this: How to mask a password in Java 5?
或者,如果您使用的是 Java 5 或更新版本,则可以使用: 如何在 Java 5 中屏蔽密码?
回答by Paul Cager
I assume this is a simulated ATM...
我假设这是一个模拟的 ATM...
Dev has pointed out that password masking on the console issupported out of the box, so you can use that. However for anything but the most trivial of IO you'd be better off using Swing or a "curses-like" library:
Dev 指出,控制台上的密码屏蔽是开箱即用的,因此您可以使用它。然而,除了最微不足道的 IO 之外,您最好使用 Swing 或“类似诅咒”的库:
回答by Dev
If you have JavaSE 6 or newer you can use Console.readPassword()
如果您有 JavaSE 6 或更新版本,您可以使用Console.readPassword()
回答by Ernest Friedman-Hill
There's a special method Console.readPassword()
for doing this, introduced in Java 6. You obviously couldn't run code like this on a real ATM, though! Swing has JPasswordField
which lets you do this kind of masking in a GUI, and one could imagine a Swing-based ATM window.
有一种特殊的方法Console.readPassword()
可以做到这一点,它在 Java 6 中引入。不过,您显然无法在真正的 ATM 上运行这样的代码!SwingJPasswordField
可以让您在 GUI 中进行这种屏蔽,您可以想象一个基于 Swing 的 ATM 窗口。