Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: eliminated System.gc()

...

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: ");

    if (!verify(username, password)) {
      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;
  }
}

Noncompliant Code Example (System.gc())

This noncompliant code example attempts to erase the password string by explicitly invoking garbage collection after verification. However, the password might still 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 = 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;
  }
}

Compliant Solution

This compliant solution uses the Console.readPassword() method to obtain the password from the console:

...