Masking password input from the console : Java


import java.io.Console;
import java.util.Arrays;

public class ConsoleMain
 {

  public static void main(String[] args)
 {
    Console console = System.console();
    String username = console.readLine("Username: ");
    char[] password = console.readPassword("Password: ");

    if (username.equals("vineeth") && String.valueOf(password).equals("vineeth"))
  {
      console.printf("Welcome to Java Application %1$s.\n", username);

      Arrays.fill(password, ' ');
    } else {
      console.printf("Invalid username or password.\n");
    }
  }
}




The idea here is that you can call Arrays. fill (or equivalent) to "blank" the char array as soon as you've validated the password, and from that point the password is no longer stored in memory.
 Since Strings are immutable, the String will remain in the heap until it is garbage collected - which if it manages to get itself interned will be never, and in any other case could still be "too long". All the while it is there, it's potentially vulnerable to sniffing from a variety of vectors.The Console object supports secure password entry through its readPassword method. This method helps secure password entry in two ways. First, it suppresses echoing, so the password is not visible on the user's screen. Second, readPassword returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.

1 comments:

Swaroop said...

The above code will return a null point exception please help me out i need to accept a password in console

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org