How to read password from command-line without echoing it back to the user?

How to read password from command-line without echoing it back to the user?

Your command-line application needs to authenticate the user and for security reasons, you don?t want to display the password on the console. Java API did not have support for this until class was introduced in JDK 1.6. Specifically, Console class has readPassword() method which can serve the purpose of reading the password from command-line securely. Here is the code snippet to prompt and read the password in one go:char[] password = console.readPassword(?Enter Password: ?);Here is a short and simple Java program that you can execute to get a feel for the Console class and especially its readPassword() method:import*;import java.util.Arrays;public class ReadPassword { public static void main(String[] args) { // Console class doesn?t provide any public constructors Console console = System.console(); String uname = console.readLine(“Enter Username: ” ); char[] password = console.readPassword(“Enter Password: “); // the below system.out?s purpose is to prove to us that the password has been correctly read System.out.println(“User: ” + uname + ” with Password: ” + new String(password) + ” is authenticated.”); // Manually erase the password character array by filling it with spaces Arrays.fill(password, ? ?); }}Notes:1. You can?t use new operator to create Console object as it has no public constructors. JVM maintains a single instance of console class which can be accessed using System.console() method.2. To prompt and read username we used Console?s readLine() method which returns String object unlike readPassword() method which returns character array3. It is a good idea to manually erase the password immediately after authenticating/processing the password so as to minimize the lifetime of sensitive data


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist