星号字符串,屏蔽密码
我正在为 ATM 机创建这个简单的登录代码。 输入用户名和密码并登录,效果非常好。由于我没有连接到数据库或外部文本文件,并且只有 1 个用户,因此它只是用 Java 代码简单地编写。但是,当您输入密码“p4ss”时,我希望它被屏蔽,因此您不应在键入时在屏幕上看到它,而应该看到“* * * *”或“ ”只是空白(就像在 Linux 上输入 pass 时一样)。
目前我的代码如下所示:
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.");
}
非常感谢我能得到的任何帮助。
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).
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Michael,看一下Sun网站上的描述:
https://web.archive.org/web/20120214061606/http://java.sun.com/developer/technicalArticles/Security/pwordmask
或者,如果您使用的是 Java 5 或更高版本,你可以使用这个:
如何在 Java 5 中屏蔽密码?
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
Or, if you're using Java 5 or newer, you can use this:
How to mask a password in Java 5?
我假设这是一个模拟 ATM...
Dev 指出控制台上的密码屏蔽是开箱即用的,因此您可以使用它。然而,除了最琐碎的 IO 之外,您最好使用 Swing 或“类似诅咒”的库:
I assume this is a simulated ATM...
Dev has pointed out that password masking on the console is supported 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:
如果您有 JavaSE 6 或更高版本,则可以使用 Console.readPassword()
If you have JavaSE 6 or newer you can use Console.readPassword()
Java 6 中引入了一个特殊的方法
Console.readPassword()
来执行此操作。但是,您显然无法在真正的 ATM 上运行这样的代码! Swing 有JPasswordField
,它可以让您在 GUI 中进行这种屏蔽,并且可以想象一个基于 Swing 的 ATM 窗口。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 hasJPasswordField
which lets you do this kind of masking in a GUI, and one could imagine a Swing-based ATM window.