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 p开发者_运维问答assword (tpyed by the user) in the String data type.
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);
Just convert the char array to a string. Console.readPassword is exactly made for your use case (reading a pwd :D).
Originally, it's char[] and not String because you can null the content of the array and your password is gone while String may gets pooled and stay in your memory.
There is an example here: Password Masking in the Java Programming Language[java.sun.com]
Just use console.readPassword()
and then make a String
from the char[]
:
String passWord = new String(chars);
Since you want to output asterisks, you cannot use console.readPassword. Instead, you have to do it on your own: disable the echoing, switch the input to unbuffered (char-wise instead of line-wise) mode, read the password char by char, print an asterisk for each char you read. I propose you look for a curses-like library for java (there are several around, see What's a good Java, curses-like, library for terminal applications?, for this task.
精彩评论