• Post Reply Bookmark Topic Watch Topic
  • New Topic

Core java password hiding  RSS feed

 
Makesh Kumar Ramakrishnan
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am developing a core java application with no swing package. It requires to take user name and password by prompting the user to key in. It needs to display '*' character whenever user enters password character on the screen.
I am using System.in to read the input.

I know, if I use swing / web jars, then it would be easier to use password field to get the password from user. My requirement is not to use either of the package.

What would be the better way to implement this functionality?

Makesh
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are using Java 6, System.console() returns a Console object which has two methods you can use: readPassword() and readPassword(String format, Object... args). When called, both will completely hide any text filled in. That means you also won't see any *s.

Please note that System.console() can return null if the Java program is not called from the command line; always check for that.
 
Makesh Kumar Ramakrishnan
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob for your quick reply.

But I am using Java 5. What is the alternative solution?

Thanks,

Makesh
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about a tiny JFrame with a JPasswordField on? That returns its password in char[] form, and fills in the field with round spots.
 
Makesh Kumar Ramakrishnan
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply Campbell. As I mentioned I need to read the user input from system console. No user input window. I know, sometimes you get weird requirements. But that is what we need to deal with.

Makesh
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I fear that using system calls with JNI is the only alternative for you.

If all characters were available and read immediately, you could erase the previous character by printing a \b (backspace) first, then *. Unfortunately, characters are only available after the user presses enter most of the time.
 
Makesh Kumar Ramakrishnan
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob for your inputs.I will try to implement the solution.

Makesh
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!