views:

68

answers:

5

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.

Any help is greatly appreciated...

+2  A: 

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.

atamanroman
+4  A: 

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);
Vivien Barousse
A: 

Just use console.readPassword() and then make a String from the char[]:

String passWord = new String(chars);
Joonas Pulakka
+1  A: 

There is an example here: Password Masking in the Java Programming Language[java.sun.com]

dogbane
A: 

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 http://stackoverflow.com/questions/439799/whats-a-good-java-curses-like-library-for-terminal-applications, for this task.

ammoQ