Search code examples
javacommand-linepasswordsmasking

Masking the password field in java


I am developing a Java command line application and I need to display an asterisk (*), or any similar sign, when the user inputs the password. I have tried using the replace() method but it accepts only one character. Is there a way to pass all the letters and numbers as an argument for this replace method. Or else what is the method of masking the suer input.

I cannot use the console.readPassword technique here, because I need the password (tpyed by the user) in the String data type.


Solution

  • Actually, you cannot use the replace method. By using it, the user input is still visible, and you're only changing the value you stored into memory.

    If you need the password as a String (that's not recommended for security reasons, but anyway...):

    char[] pwd = console.readPassword();
    String str = new String(pwd);