Link to home
Start Free TrialLog in
Avatar of 4eyesgirl
4eyesgirl

asked on

What function I can use to hide user input password in java?

Hi expert,

I want to write a simple program that will ask user password, but i don't want the actual passeord character being print on the screen.  Is there a way to do it in Java?  If so, can you plese provide some sample code.

THX
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You can use a JPasswordField
Avatar of 4eyesgirl
4eyesgirl

ASKER

I am not using the textbox, so can this work for command line program?

System.in.read()?
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In Java SE 6 there is a new class added: java.io.Console

Console cons;
char[] passwd;
if ((cons = System.console()) != null &&
    (passwd = cons.readPassword("[%s]", "Password:")) != null) {
    ...
    java.util.Arrays.fill(passwd, ' ');
}

Before Java SE 6 there was no support to read passwords from console, although you can find some tricks that can get you close, but none of them works 100%.

As CEHJ says, in swing there's a JPasswordField, but this will require you to at least display a dialog window.
Bart Cr:

Does your code work?  I just copied the abovce code and System.console() is always null, why?
How do you launch the program. When I launch it from an IDE the System.console() will be null, launching it from command line, it works (for me).
CeJH -

Did you try the code from the http://java.sun.com/developer/technicalArticles/Security/pwordmask/ ?  I cannot get it run...it hangs at
class readPassword -
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String password = "";


Enter password: ****************************************
That's what I meant with tricks that do not work 100%
I launch the progrma from the IDE< so I cannot launch it from eclipse?
The IDE will replace the System.in and System.out with its own streams to capture program output. Sadly enough the input doesn't work to well.
So this track only works for command line correct?  

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:-)