Masking password in Java CLI application - java

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.

Related

Not able to run password masking using char[] PASSWORD =cons.readPassword in gitbash terminal

hi im trying to run this programme for password masking using char[] PASSWORD =cons.readPassword()
but it is giving me
Exception in thread "main" java.lang.NullPointerException
at automateCFOSetup.App.main(App.java:32)
when i ran the programme in git bash terminal. But when i ran it on Windows cmd it was running fine...any reason why this occurred as i am only aware of issue of getting this null pointer when running within IDE
this is my code
Scanner scan = new Scanner(System.in);
Console cons = System.console();
log.info("ENTER YOUR ID :");
String SOEID = scan.nextLine();
char[] PASSWORD =cons.readPassword("ENTER YOUR PASSWORD :");
scan.close();
Any help with this?
A console is not guaranteed to support this feature. Given that you're getting the exception, the particular console you use here (your IDE and I'm not surprised - those 'consoles' for some reason don't usually support this), does not support password input.
There is no solution to this. But there are workarounds:
You can catch the exception and tell the user: Tough luck - no can do.
You can catch it, and decide, eh, whatever, ask with the usual tricks (scanner.nextLine()). Perhaps warn the user that their pw will be echoed. Surely, 'run it in the IDE' isn't how you intend to deploy your software, so this isn't all that much of a security issue (if this app is used on private developer's laptops, generally those already contain so much information, such as the code itself, git keys, etc - if that device is compromised, you have much bigger problems already).
Don't ask on the console at all, instead, get that password from elsewhere, such as a file, using PKI. Passwords are so 1990, you know.

How to block command prompt from showing my password while I'm inputting it to my java program [duplicate]

This question already has answers here:
Masking password input from the console : Java
(5 answers)
Closed 9 years ago.
So I have this application, where I read users input from command prompt, and when user is inputting his/her password, I would like to hide it such that everyone else cant see it like this:
Please enter your password below
this is password
I would like to show it like this:
Please enter your password below
****************
So is there any way of doing this in java console application?
Take a look at the Console class, it has readPassword()
Syntax:
public char[] readPassword(String fmt,Object... args)
Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled.
Parameters:
fmt - A format string as described in Format string syntax for the prompt text.
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers,
the extra arguments are ignored. The maximum number of arguments is
limited by the maximum dimension of a Java array as defined by the
Java Virtual Machine Specification.
Returns - A character array containing the password or passphrase read from the console, not including any line-termination
characters, or null if an end of stream has been reached.
Taken from the answer pointed in the comment:
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char passwordArray[] = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
The thing to notice is that you are getting back a char[] and not a String. This is for security reasons and there is another great answer on this same topic on SO. You should destroy this char[] by overwriting it after your work is done. Strings can stay a longer time in memory till the GC collects them and this can be a security risk.
Run the example from the command line and not from an IDE. It may not work.

Regex submitting with empty string

I have the following REGEX that I'm serving up to java via an xml file.
[a-zA-Z -\(\) \-]+
This regex is used to validate server side and client side (via javascript) and works pretty well at allowing only alphabetic content and a few other characters...
My problem is that it will also allow zero lenth strings / empty through.
Does anyone have a simple and yet elegant solution to this?
I already tried...
[a-zA-Z -\(\) \-]{1,}+
but that didn;t seem to work.
Cheers!
UPDATE FOLLOWING INVESTIGATION
It appears the code I provided does in fact work...
String inputStr = " ";
String pattern = "[a-zA-Z -\\(\\) \\-]+";
boolean patternMatched = java.util.regex.Pattern.matches(pattern, inputStr);
if ( patternMatched ){
out.println("Pattern MATCHED");
}else{
out.println("NOT MATCHED");
}
After looking at this more closely I think the problem may well be within the logic of some of my java bean coding... It appears the regex is dropped out at the point where the string parse should take place, thereby allowing empty strings to be submitted... And also any other string... EEJIT that I am...
Cheers for the help in peer reviewing my initial stupid though....!
Have you tried this:
[a-zA-Z -\(\) \-]+

String to asterisk, masking password

I'm creating this simple login code for an ATM machine.
You enter username and password and you logs in, that works just great. Since I'm not connecting to a database or an external text file and I've just got 1 user, it's just written plainly in the Java code. But when you enter the password "p4ss" I want it to be masked, so instead of seing it on the screen while typing you should see "* * * *" or " " just blank (Like when you enter pass on Linux).
Currently my code looks like this:
String user;
String pass;
System.out.print("User: ");
user = Keyboard.readString();
System.out.print("Pass: ");
pass = Keyboard.readString();
if ((user.equals("Admin")) && (pass.equals("p4ss")))
{
menu();
}
else
{
out.println("Wrong username or password.");
}
Would appreciate any help I could get.
Michael, have a look at the description on Sun's website:
https://web.archive.org/web/20120214061606/http://java.sun.com/developer/technicalArticles/Security/pwordmask
Or, if you're using Java 5 or newer, you can use this:
How to mask a password in Java 5?
I assume this is a simulated ATM...
Dev has pointed out that password masking on the console is supported out of the box, so you can use that. However for anything but the most trivial of IO you'd be better off using Swing or a "curses-like" library:
http://www.pitman.co.za/projects/charva/index.html
http://sourceforge.net/projects/javacurses/
If you have JavaSE 6 or newer you can use Console.readPassword()
There's a special method Console.readPassword() for doing this, introduced in Java 6. You obviously couldn't run code like this on a real ATM, though! Swing has JPasswordField which lets you do this kind of masking in a GUI, and one could imagine a Swing-based ATM window.

J2ME converter program not accepting user's input

I am having problems with my converter program not accepting the value the user inputs. Everything seems so right but the result is always as if the user entered nothing. If anyone can just point me in the right direction I would greatly appreciate it!
my project consists of 2 files (1 midlet and 1 class).
code was too long to post on this forum so I uploaded the zip.
Edit hosted here now should be cleaner: removed
I can't really narrow it down to a small piece of code because it could be any number of things which I have already tried. I know its asking quite a bit but the code isn't insanely long. I'd be extremely grateful if anyone could take a look.
edit 2: the file seems to be trying to download an image... here is the code in another forum i posted in but got no answers.: http://www.codingforums.com/showthread.php?p=1024059#post1024059
edit 3: here is where I think the problem lies in the code:` public double customForm (String fName)
{
ui_form = new Form(fName);
ui_form.addCommand(Convert);
ui_form.addCommand(Back);
display.setCurrent(ui_form);
num = new TextField("Enter the number of units you would like to convert", "", MAX_CHARS, TextField.ANY);
ui_form.append(num);
ui_form.setCommandListener(this);
/***********************/
/* THIS IS NOT WORKING*/
// str = num.getString();
str = "The number is: " + num.getString();
try
{
numUnits = Double.parseDouble(str);
}
catch (NumberFormatException nfe)
{
}
finally
{
return numUnits;
}
//return str;
}
`
but you will probably need to look at the rest of the code to see where the problem lies. this is just the root i think
You cannot read the text field right after it has been added to a form. It looks like you assumed the num.getString() method to block until there's user input - this is not the case. User input is provided asynchronously, i.e. you should read the text field's content in response to a user command, somewhere in the commandAction() method (in your case when the Convert command has been issued by the user).
Handling user events asynchronously is a core pattern in GUI development. In this regard I recommend to read some example code for command handling in JavaME, for instance this or this.

Categories