6

The standard JVM method for reading a password from the command line without showing it is java.io.Console.readPassword(). This, however, shows nothing while the user is typing; users accustomed to graphical programs will expect symbols such as "•" or "*" to appear in place of the characters they type. Naturally, they will also want backspacing, inserting, and so on to work as normal, just with all the characters being operated on replaced with the same symbol.

In 2019, is there a generally accepted JVM procedure for showing "*******" when the user types "hunter2" in a console application? Can this even be done properly without a GUI? A 2011 SO question on the topic got an answer linking to this article on the topic; can we do better nowadays than the rather elaborate solution shown therein?

(I happen to be using Kotlin as my language of choice, so a Kotlin-specific solution will satisfy if there is one.)

Shay Guy
  • 1,010
  • 1
  • 10
  • 21

2 Answers2

0

hunter2? Wow. Reference acknowledged.

There is no easy way. The primary problem is that the standard System.in doesn't give you any characters at all until the user has pressed enter, so there's no way to emulate it (if you try to read char-for-char from System.in and emit a * every time a key is pressed, that won't work).

The lanterna library at https://github.com/mabe02/lanterna can do it, though. If you want to emulate it, it's.. very complicated. It has branching code paths for unix and windows. For example, on unix, it uses some hackery to figure out what tty you're on, and then opens the right /dev/tty device. With lanterna, writing this yourself would be trivial.

It's that or accept Console.readPassword()'s blank nothingness, really. Or, write a web interface or a swing/awt/javafx GUI.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
-1

I think answer to your question can be found here in stackoverflow itself. please see this:

masking-password-input-from-the-console-java

sample code from there:

import java.io.Console;
public class Main {

    public void passwordExample() {        
        Console console = System.console();
        if (console == null) {
            System.out.println("Couldn't get Console instance");
            System.exit(0);
        }

        console.printf("Testing password%n");
        char passwordArray[] = console.readPassword("Enter your secret password: ");
        console.printf("Password entered was: %s%n", new String(passwordArray));

    }

    public static void main(String[] args) {
        new Main().passwordExample();
    }
}

hope this is helpful. :)

Dilanka M
  • 372
  • 1
  • 5
  • 17
  • The string "Enter your secret password: " just provides a prompt. It doesn't set readPassword() to show placeholder characters. – Shay Guy Jan 08 '19 at 02:07