如何在 Java 5 中屏蔽密码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1108937/
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
How to mask a password in Java 5?
提问by Chathuranga Chandrasekara
I am trying to mask a password in Java. Sun java has suggested a way to mask a password as follows.
我正在尝试用 Java 屏蔽密码。Sun java 提出了一种掩码密码的方法,如下所示。
It uses a simple way to do that.
它使用一种简单的方法来做到这一点。
public void run () {
stop = true;
while (stop) {
System.out.print("0*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
But this approach has several drawbacks.
但是这种方法有几个缺点。
If the user uses the arrow keys + delete keys the password gets revealed.
If the user accidentally press 2 keys at the same time (Extremely high typing speed) some characters does not get masked.
如果用户使用箭头键 + 删除键,密码就会显示出来。
如果用户不小心同时按下 2 个键(极高的打字速度),某些字符不会被屏蔽。
Do you guys think of any way that can get a 100% correct masking?
你们有没有想出任何方法可以获得 100% 正确的掩蔽?
回答by Bombe
回答by Pierre
You can now use System.console();
您现在可以使用System.console();
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
char [] password = c.readPassword("Enter your password: ");
回答by dfa
Using certain syscalls (on windows and unix) you can disable echoing of characters to console. This is what System.console() does, but it works also in Java.
使用某些系统调用(在 Windows 和 unix 上),您可以禁用字符回显到控制台。这就是 System.console() 所做的,但它也适用于 Java。
I'm using JNA to map certain syscall of unix and windows in a private branch of jline:
我正在使用 JNA 在 jline 的私有分支中映射 unix 和 windows 的某些系统调用:
- on unix I'm using the termiosstructure and tcgetattr/tcsetattr
- on windows I'm using GetConsoleModeand SetConsoleMode.
- 在 unix 上我使用termios结构和tcgetattr/tcsetattr
- 在 Windows 上,我使用GetConsoleMode和SetConsoleMode。
If you need code example leave a comment.
如果您需要代码示例,请发表评论。
回答by Benoit Courtine
With the JDK 6.0, you have the java sources of the classes, including Console : I just verified and this class has only Java 5.0 dependencies.
使用 JDK 6.0,您拥有类的 Java 源代码,包括 Console :我刚刚验证过,这个类只有 Java 5.0 依赖项。
So, in your project, you can create a copy of this Console class, and then use the readPassword method. I did not try but it should work.
因此,在您的项目中,您可以创建此 Console 类的副本,然后使用 readPassword 方法。我没有尝试,但它应该工作。

