Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking password input from the console : Java

How to mask a password from console input? I'm using Java 6.

I've tried using console.readPassword(), but it wouldn't work. A full example might help me actually.

Here's my code:

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test 
{   
    public static void main(String[] args) 
    {   
        Console console = System.console();

        console.printf("Please enter your username: ");
        String username = console.readLine();
        console.printf(username + "\n");

        console.printf("Please enter your password: ");
        char[] passwordChars = console.readPassword();
        String passwordString = new String(passwordChars);

        console.printf(passwordString + "\n");
    }
}

I'm getting a NullPointerException...

like image 425
New Start Avatar asked Nov 15 '11 15:11

New Start


People also ask

How to do masking of password in Java?

To mask the password field, use the setEchoChar method. For example, to set the echo char to an asterisk, you would do: TextField password = new TextField(8); password.

Why is system console null?

System. console() returns null if there is no console. You can work round this either by adding a layer of indirection to your code or by running the code in an external console and attaching a remote debugger.


2 Answers

A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)

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();
    }
}
like image 83
bilash.saha Avatar answered Sep 30 '22 23:09

bilash.saha


You would use the Console class

char[] password = console.readPassword("Enter password");  
Arrays.fill(password, ' ');

By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.

If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained

like image 8
Woot4Moo Avatar answered Oct 01 '22 00:10

Woot4Moo