简体   繁体   中英

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.

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).

This site has an example of pretty much exactly what you are trying to do: http://download.oracle.com/javase/tutorial/essential/io/cl.html

To be thorough, here are two more links to similar tutorials.


Do they answer your question?


Based on your comments, perhaps you do not understand Java syntax exactly.

You cannot write:

char["mypassword"] passwd;

I think you mean instead:

String str = "mypassword";
char[] passwd = str.toCharArray();

Update

Try this code:

Console c = System.console();
if (c == null) {
    System.err.println("No console.");
    System.exit(1);
}

char [] passwd = c.readPassword("Enter your password: ");

c.println("Password is:");
c.println(new String(passwd));

Take a look at this sun Java article ... it highlights a number of different ways to do it.

Specifically it shows how to use AWT's TextField class with the setEchoChar() method, as well as a method that runs a separate thread to remove and replace typed characters in console applications.

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