Mask input in Java

Status
Not open for further replies.

redhat

Mad and Furious
Hey friends,
I am working on a project and need to mask the input taken with a '*'
Can someone please tell me the procedure to do so?

Thanks a lot....
 

QwertyManiac

Commander in Chief
If you are using AWT or Swing you can use the following Echoing Character specifier as below respectively:

AWT
Code:
TextField pwd = new TextField(someInt);
pwd.setEchoChar('*');

Swing
Code:
JPasswordField pwd = new JPasswordField(someInt);
pwd.setEchoChar('*');

For command line, its sort of difficult I guess cause you need to use the Console class.

An example would be like thus:
Code:
import java.io.Console;

public class Password
{
	public static void main (String args[])
	{
		Console c = System.console();
		String id = c.readLine("ID: ");
		char [] pass = c.readPassword("Pass: ");
	}
}

On UNIX consoles like mine it doesn't echo anything, I don't know about Windows, must show an asterix though.

Remember that readPassword method of Console returns a char [] and not String. :)

Umm, redhat deleted your post? I was gonna flame! Come back! :p
 
Last edited:
OP
redhat

redhat

Mad and Furious
@Shirish_nagar: Thanks for your reply.
But, I still have a problem...
I worked exactly as the Tutorial on the link said.(I am using Command Line)
But, the loop that adds the mask, always enters an infinite loop, even before the user can enter input.

Please help me with this...
 

Faun

Wahahaha~!
Staff member
Due to the System independant nature of Java, Java is unable to mask character input on the command line. Thus, all passwords typed in via Standard In, are visible in plain text.

U will have to use a maskable thread running to replace the password entered.

Guess u need to learn threading :D
*forum.java.sun.com/thread.jspa?threadID=141432&messageID=388912
 

QwertyManiac

Commander in Chief
redhat said:
@Shirish_nagar: Thanks for your reply.
But, I still have a problem...
I worked exactly as the Tutorial on the link said.(I am using Command Line)
But, the loop that adds the mask, always enters an infinite loop, even before the user can enter input.

Please help me with this...
:confused: Didn't I already write a piece of code for Console input?

Do you need an even practical example?
Code:
import java.io.Console;

public class Password
{
    public static void main (String args[])
    {
        Console c = System.console();
        String id = c.readLine("ID: ");
        char [] pass = c.readPassword("Pass: ");
        String pasw = new String(pass);
        if(id.equals("Hello")&&pasw.equals("World"))
        {
            System.out.println("\nCorrect.\nWelcome to the Matrix (Cliche'd, I know)");
        }
        else
        {
            System.out.println("\nWrong.\nIn Soviet Russia, the Password has YOU.");
        }
    }
}
Outputs as:
Code:
#Correct Password try "World"
harsh@harsh-workstation:~$ java Password
ID: Hello
Pass: 

Correct.
Welcome to the Matrix (Cliche'd, I know)
#Wrong password try "Wrong"
harsh@harsh-workstation:~$ java Password
ID: Hello
Pass: 

Wrong.
In Soviet Russia, the Password has YOU.

# Console doesn't allow echoing. That's being smart. Than letting people count your asterixes (*)
Using - Console class

If you need the AWT code, do ask.

Edit: Adding the free online code for Java 2: The Complete Reference demonstrating the password box anyway:
Code:
// Demonstrate text field. - Herbert Schildt 
import java.awt.*; 
import java.awt.event.*; 
import java.applet.*; 
/* 
  <applet code="Password" width=380 height=150> 
  </applet> 
*/ 
 
public class Password extends Applet 
  implements ActionListener { 
 
  TextField name, pass; 
 
  public void init() { 
    Label namep = new Label("Name: ", Label.RIGHT); 
    Label passp = new Label("Password: ", Label.RIGHT); 
    name = new TextField(12); 
    pass = new TextField(8); 
    pass.setEchoChar('*'); 
 
    add(namep); 
    add(name); 
    add(passp); 
    add(pass); 
 
    // register to receive action events 
    name.addActionListener(this); 
    pass.addActionListener(this); 
  } 
 
  // User pressed Enter. 
  public void actionPerformed(ActionEvent ae) { 
    repaint(); 
  } 
 
  public void paint(Graphics g) { 
     g.drawString("Name: " + name.getText(), 6, 60); 
     g.drawString("Selected text in name: " 
                  + name.getSelectedText(), 6, 80); 
     g.drawString("Password: " + pass.getText(), 6, 100); 
  } 
}
This creates an applet with an ID and Password text fields.

And from Shrish_nagar's link, here's the working file (Added as attachment).
 
Last edited:

Faun

Wahahaha~!
Staff member
Okie i hav tested this program

here is the output (it still not perfect):

C:\prog\java\pass>java TestApp
Enter password:****************a***********************************************j
************i****************************************************i*************h
*******j***************************h*********************d*********************c
****d****************************j*********************************************f
*******************i************************************k*********k************g
***************************n****************
The password entered is: sudlsdklasjkldjasdwiorjlwejiopds fjhdsfk./asm;ldfwjekul
rhqpwajajkaaskdklsf;ioefiwejfdklfkjdfds;ljfjdsgfjshedskjkslskskskjasidquwiorywer
yuwehrdhsfjldkjlcdjvhjlfhds;klihgfidshfioshaglihgidhighprugoegkldsjklfhdsklcn;ln
ckldshckjldhsfioydhsaifueifew;kljfre;kljtrutopreugidsjgkldj;klfjds;klfjds;ojfoes
ufdajfkdsnvklbdkjbkugeutiret0rkhgfhgjfdslhgdsiahf8oaydfwiejf;klesfldsm;klvcdbkjv
kldjgds;lojfiafjfkesjaf;lasjffknbgireugpjregrejg

C:\prog\java\pass>

The Bad:
1) Clearly some chars are visible if user types the password rapidly
2) Invariably the chars will be visible, and we hav no control over threads (when it becomes runnable again), depends totally on process queue manager.
3) Excessive threading.
4) Asterisk before entering a password.

The Good:
1) Password is masked.
 
Last edited:
Status
Not open for further replies.
Top Bottom