简体   繁体   中英

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.

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.

这里有一个示例: Java编程语言 [java.sun.com] 中的密码屏蔽

只需使用console.readPassword() ,然后从char[]创建一个String

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM