# Mask input in Java



## redhat (Nov 25, 2007)

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


----------



## Garbage (Nov 25, 2007)

Have a look @ this Redhat.

And some thing ( JPasswordField in Swing ) from here


----------



## QwertyManiac (Nov 26, 2007)

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

AWT

```
TextField pwd = new TextField(someInt);
pwd.setEchoChar('*');
```

Swing

```
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:

```
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!


----------



## redhat (Nov 28, 2007)

@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 (Nov 28, 2007)

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 
*forum.java.sun.com/thread.jspa?threadID=141432&messageID=388912


----------



## QwertyManiac (Nov 29, 2007)

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


 Didn't I already write a piece of code for Console input?

Do you need an even practical example?

```
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:

```
#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:

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


----------



## Garbage (Nov 29, 2007)

Thanks QM for explanation !!

This time, u r faster than me !!


----------



## Faun (Nov 29, 2007)

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



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.


----------

