Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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: ");
- /*
- 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.
- */
- String password = c.readLine("Enter your password: ");
- if (!verify(username, password)) {
- throw new SecurityException("Invalid Credentials");
- }
- // ...
- }
- // Dummy verify method, always returns true
- private static final boolean verify(String username,
- String password) {
- return true;
- }
- }
- //Compliant Solution
- 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: ");
- /*
- Console.readPassword() method allows the password to be returned as a sequence of characters rather than as a String object.
- */
- char[] password = c.readPassword("Enter your password: ");
- if (!verify(username, password)) {
- throw new SecurityException("Invalid Credentials");
- }
- // Clear the password
- Arrays.fill(password, ' ');
- }
- // Dummy verify method, always returns true
- private static final boolean verify(String username,
- char[] password) {
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement