How to block command prompt from showing my password while I'm inputting it to my java program [duplicate]

StackOverflow https://stackoverflow.com/questions/20211619

Question

So I have this application, where I read users input from command prompt, and when user is inputting his/her password, I would like to hide it such that everyone else cant see it like this:

Please enter your password below
this is password

I would like to show it like this:

Please enter your password below
****************

So is there any way of doing this in java console application?

Était-ce utile?

La solution

Take a look at the Console class, it has readPassword()

Syntax:

public char[] readPassword(String fmt,Object... args)

Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled.

Parameters:

fmt - A format string as described in Format string syntax for the prompt text.

args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification.

Returns - A character array containing the password or passphrase read from the console, not including any line-termination characters, or null if an end of stream has been reached.

Autres conseils

Taken from the answer pointed in the comment:

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();
}
}  

The thing to notice is that you are getting back a char[] and not a String. This is for security reasons and there is another great answer on this same topic on SO. You should destroy this char[] by overwriting it after your work is done. Strings can stay a longer time in memory till the GC collects them and this can be a security risk.

Run the example from the command line and not from an IDE. It may not work.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top