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
Why Do I Get Java.Lang.Abstractmethoderror When Trying to Load a Blob in the Db
Connect 4 Check for a Win Algorithm
How to Go About Formatting 1200 to 1.2K in Java
Does Polymorphism Apply on Class Attributes in Java
How to Connect SQLite with Java
Adding N Hours to a Date in Java
Can a Java File Have More Than One Class
Post Request Send JSON Data Java Httpurlconnection
Whitespace Matching Regex - Java
What Is the Default Encoding of the Jvm
Jdbc MySQL Connection Pooling Practices to Avoid Exhausted Connection Pool
Java Null Check Why Use == Instead of .Equals()
What's the Difference Between <> and <? Extends Object> in Java Generics