Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java Console read password

farenda 2015-12-22 0

Problem:

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

Solution:

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.

package com.farenda.java.io;

import java.io.Console;
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 =
                encoder.encodeToString("javarules!".getBytes(UTF_8));

        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(Objects.java:228)
      at com.farenda.java.io.ConsoleReadPasswordExample.main(ConsoleReadPasswordExample.java:15)

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

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

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

Share with the World!
Categories Java Tags java, java-io
Previous: Spring component scan exclude
Next: JUnit Getting Started

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored