Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking password in Java CLI application

I've made this little ATM application in Java (CLI) and in the beginning I want to have "Code: " and then the user should enter it, and in my Java application it should say something like String(or int?) code = 1234; and if that works then proceed, if not wrong, try again, if faulty 3 times, stop app.

How would something like that look? I've been googling for hours now after masked passwords and tried different types of code without any luck. I just want something simple that converts the string to asterisk.

Currently my password masking looks like this:

java.io.Console cons;
char[] passwd;

if ((cons = System.console()) != null && (passwd = cons.readPassword("[%s]", "Code:")) != null)

However I'm not able (don't know) how to set a password in the code.

like image 679
Michael Avatar asked Jul 23 '26 18:07

Michael


1 Answers

Use the readPassword method of class java.io.Console.

The API documentation of class Console has an example that shows how to read a password from the console window without echoing it in plaintext.

edit

Michael, this code is to let a user enter a keyword in the console window without displaying it. After the user has done that, the password is stored in the variable passwd. It seems that what you really want is something completely different: you have some other program that asks for a password, and you want your program to enter that password automatically.

If that is indeed what you want to do, then you don't need to use class Console. You could try using class java.awt.Robot to enter keystrokes in another application (but I'm not sure that it would work with a console window - try it out).

like image 155
Jesper Avatar answered Jul 25 '26 06:07

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!