Masking Password Input from the Console:Java

Masking password input from the console : Java

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();
}
}

Hide Password Input On Console Window

Use the Console readPassword() method:

 char[] passwd = System.console().readPassword("[%s]", "Password:");

Hide Password From Console Window Java Asterisk Password Or Block Inputted String Being Displayed

Use the readPassword() method.

instead of using scanner like

System.out.println("Please Enter Password");
pass = sc.nextLine();

use:

    System.out.println("Please Enter Password");
char[] passString = Console.readPassword();
String pass = new String(passString );

How to encrypt the user input(for ex : password) in java output console

JDK provides Console class to handle these scenarios, it provides readPassword to read password by masking, it doesn't display *'s though.

Here is a small example.

import java.io.Console;
public class Library {
public static void main(String[] args) {
Console console = System.console();
char[] passwordArray = console.readPassword("Enter your password: ");
console.printf("Password is: %s%n", new String(passwordArray));
}
}

Note: This only works with System's console, doesn't work with IDE.



Related Topics



Leave a reply



Submit