如何在不使用 System.console() 的情况下从控制台读取密码?

2022-01-22 00:00:00 console passwords security java

我遇到 这个 Eclipse 错误,其中 System.console() 不适用于 Java 应用程序启动.我有一个小型 Java 应用程序,该应用程序还需要输入只能从 IDE 内启动的密码.有没有其他方法可以安全地仅使用 JDK 类从控制台读取密码(即不在控制台上显示)?

I hit this eclipse bug, where System.console() is not available for Java application launches. I have a small Java app that also requires a password to be entered that is only started from within the IDE. Is there any other way to safely read a password (meaning not displaying it on the console) from the console with only using JDK classes?


我知道 System.in,但那是在控制台中显示输入的字符,因此不安全.


I know of System.in, but that is displaying the inputed characters in the console and is therefore not safe.


我还想指出,可以在项目中的 windows 下创建批处理文件或 linux/unix 下的小 bash 脚本.通过使用系统默认编辑器在 eclipse 中打开此文件,它将在 System.console() 可用的新控制台窗口中启动.这样您就可以从 Eclipse 中启动应用程序.但必须先构建项目,以便二进制文件存在.


I also want to note that one can create a batch file under windows or a small bash script under linux/unix in the project. By openening this file in eclipse with the system default editor, it will be started in a new console window where System.console() is available. This way you can start the application from within eclipse. but the project has to be built first, so that the binaries exist.

推荐答案

如果System.console()返回null,表示目前没有可用的控制台就Java而言.

If System.console() returns null, that means that there is no usable console as far as Java is concerned.

  • 您不能使用 System.in,因为它可能没有连接到控制台.

  • You can't use System.in because the chances are that it is not connected to a console.

即使可以,也没有可移植的方法来关闭 Java 中的回显.

Even if you could, there is no portable way to turn off echoing in Java.

您也许可以使用 Swing(或其他)弹出一个窗口来询问密码,但如果系统是无头的,那将无法工作.

You might be able to use Swing (or whatever) to pop up a window to ask for the password, but if the system is headless that won't work.

如果您准备做非便携式的事情,那么(在 Linux/UNIX 上)您可以尝试打开/dev/console"或/dev/tty".然后您可以使用 termios 将 tty 驱动程序置于 noecho 模式.但是您至少需要在本机代码中执行其中的一些操作.

If you are prepared to do non-portable things, then (on Linux / UNIX) you could try opening "/dev/console" or "/dev/tty". And then you could use termios to put the tty driver into noecho mode. But you'll need to do at least some of this in native code.

相关文章