Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Console read password


How to read password from Java Console in a secure way? Thanks to that came with Java 6 this task became easy.


In the following example we’re going to encode expected password with Base64 encoder and then read user’s input. When we read user’s password from the console we encrypt it in the same way and compare with original one.


import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;

import static java.nio.charset.StandardCharsets.UTF_8;

public class ConsoleReadPasswordExample {

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

        Objects.requireNonNull(console, "Run only as console application!");

        Base64.Encoder encoder = Base64.getEncoder();
        String encryptedPassword =

        String username = console.readLine("Username: ");
        char[] password = console.readPassword("%s password: ", username);

        if (password != null) {
            String providedPassword = encoder.encodeToString(
                    new String(password).getBytes(UTF_8));

            // for security reasons delete password from memory:
            Arrays.fill(password, 'x');

            if (encryptedPassword.equals(providedPassword)) {
                console.printf("Access Granted!%n");
            } else {
                console.printf("Wrong username or password!%n");

A thing to note is that the Console object is not available when the application is not run… from a console (e.g. from an IDE), else the following happens:

Exception in thread "main" java.lang.NullPointerException: Run only as console application!
      at java.util.Objects.requireNonNull(

So we have to start the application from the command line:

[farenda]$ java -cp out
Username: farenda
farenda password:
Wrong username or password!
[farenda]$ java -cp out
Username: farenda
farenda password:
Access Granted!

Nice thing is that the password is not shown when typing.

Share with the World!