Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example reads user name and password information from the console and stores the password as a String object. The credentials remain exposed until the garbage collector reclaims the memory associated with this String. While this method explicitly invokes System.gc() after verification, it is possible for the password to to not be garbage-collected. For example, this can happen if the password string matches a pre-existing string in the program.

Code Block
bgColor#FFCCCC
class Password {
  public static void main (String args[]) throws IOException {
    Console c = System.console();
    if (c == null) {
      System.err.println("No console.");
      System.exit(1);
    }

    String username = c.readLine("Enter your user name: ");
    String password = c.readLine("Enter your password: ");

    boolean isValidUser if= (!verify(username, password); 


    // Clear the password
    password = null;
    System.gc();


    if (!isValidUser) {
      throw new SecurityException("Invalid Credentials");     
    }

    // User is authorized, continue...
  }

  // Dummy verify method, always returns true   
  private static final boolean verify(String username, String password) {
    return true;
  }
}

...

Code Block
bgColor#ccccff
class Password {
  public static void main (String args[]) throws IOException {
    Console c = System.console();
    
    if (c == null) {
      System.err.println("No console.");
      System.exit(1);
    }

    String username = c.readLine("Enter your user name: ");
    char[] password = c.readPassword("Enter your password: ");
  
  boolean isValidUser if= (!verify(username, password); 


    // Clear the password
    Arrays.fill(password,' ');
    password = null;
    System.gc();


    if (!isValidUser) {
      throw new SecurityException("Invalid Credentials");     
    }
  
    // ClearUser theis password
    Arrays.fill(password, ' ');authorized, continue...
  }

  // Dummy verify method, always returns true   
  private static final boolean verify(String username, char[] password) {
    return true;
  }
}

...