Subscribe to Stuck in an Infiniteloop        RSS Feed
-----

Password Validation in Java via Regex

Icon 1 Comments
I had never used Regex before, so I decided to put together a little app using it in Java.

What do passwords typically "require"?

  • Lower case letters
  • Upper case letters
  • Digits [numbers]
  • Symbols
  • A certain length


There's two ways to approach that data set. The first way is to do a "full" regex check and then simply tell the user they passed or not, but who doesn't like visual confirmation of something? The second choice would be to have individual checks and let the user know what parts they have/are missing.

I originally made up some images that were loaded through an enum and then passed to the array of holders for each one, but considering this required a repaint and that there were no other paintable type objects (just swing components) I changed this to an un-editable JTextField whose background color changes based on the condition therein.

Some screenshots:

Attached Image

Below is the source:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * @author Knowles
 *  Encapsulates all of the visual elements of the password strength program
 */
public class PasswordGUI extends JFrame {
    private Dimension dimension;
    private JPanel panel, indicatorHalf;
    private JTextField inputField;
    private JLabel percentLabel;
    private double percentage, numCompleted;
    private final double total = 5;
    private final int frameSize = 300;

    //full and partial regexes
    private String fullRegex = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
    String[] partialRegexChecks ={
        ".*[a-z]+.*", //lower
        ".*[A-Z]+.*", //upper
        ".*[\\d]+.*", //digits
        ".*[@#$%]+.*" //symbols
    };
    String[] qualifiers = {
        "Lower case letters",
        "Upper case letters",
        "Digits [0-9]",
        "Symbols: $ % # @",
        "Length: 6-20 characters"
    };
    private JTextField[] indicators;

    public PasswordGUI(){
        //get this for later
        dimension  = Toolkit.getDefaultToolkit().getScreenSize();

        percentage = numCompleted = 0;
        this.setSize(frameSize, frameSize);
        this.setTitle("Password Strength Tester");

        inputField = new JTextField("Enter a password");
        inputField.setSize(50, 20);
        inputField.addKeyListener(new KeyListener(){
            public void keyPressed(KeyEvent e){
            }
            public void keyReleased(KeyEvent e){
                testPassword();
            }
            public void keyTyped(KeyEvent e){
            }

            private void testPassword(){
                numCompleted = 0;
                String contents = inputField.getText();
                contents = contents.trim();
                int length = contents.length();

                //partial matching
                for(int i = 0; i < partialRegexChecks.length; i++){
                    if(contents.matches(partialRegexChecks[i])){
                        numCompleted++;
                        indicators[i].setBackground(Color.GREEN);
                    }
                    else{
                        indicators[i].setBackground(Color.RED);
                    }
                }
                if((length >= 6) && (length <= 20)){
                   // System.out.println("Length between 6 and 20");
                    numCompleted++;
                    indicators[4].setBackground(Color.GREEN);
                }
                else{
                    indicators[4].setBackground(Color.RED);
                }
                //full matching
                if(contents.matches(fullRegex)){
                    inputField.setBackground(Color.GREEN);
                }
                else{
                    inputField.setBackground(Color.RED);
                }
                //numerical display
                if(numCompleted != 0) percentage = numCompleted/total *100;
                else percentage = 0;
                percentLabel.setText(percentage + "%");
            }
        }
        );

        percentLabel = new JLabel(percentage + "%");

        //handles text input/actionlisteners and percentage [numerically]
        panel = new JPanel();
        panel.setLayout(new GridLayout(2,1,5,5));
        panel.add(inputField);
        panel.add(percentLabel);

        //visual display of password attributes
        indicatorHalf = new JPanel();
        indicatorHalf.setLayout(new GridLayout(5,1,5,5));
        //use "boxes" with red/green fills as opposed to images
        indicators = new JTextField[5];
        for(int i = 0; i < indicators.length; i++) {
            indicators[i] = new JTextField(qualifiers[i]);
            indicators[i].setEditable(false);
            indicators[i].setBackground(Color.RED);
            indicatorHalf.add(indicators[i]);
        }

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(2,1,10,10));
        this.add(panel);
        this.add(indicatorHalf);
        //move to close to the middle of the user's screen
        this.setLocation(dimension.width/2-frameSize/2, dimension.height/2-frameSize/2);
        this.setVisible(true);
    }
}



/**
 * @author Knowles
 *  Password guidelines:
 * -Include numbers, symbols, upper/lowercase letters
 * -6-20 characters
 *
 * In all, 5 checks will be performed
 * The user receives a visual indication of password strength
 */
public class PasswordStrengthChecker {
    public static void main(String[] args){
        new PasswordGUI();
    }
}




As previously mentioned I hadn't done any work with Regex before, so checking for one type of character had me beating my head against the wall for a period of time. For example, [A-Z]+ says, check to see there's at least one upper case letter. Well, if you have anything else in there, it fails...eventually I decided to write the regex as I would say the validation out loud, using this handy cheat sheet, I ended up with .*[A-Z]+.* which basically says zero or more "any characters" and at least one uppercase letter.


Let me know what you think. Happy coding!

1 Comments On This Entry

Page 1 of 1

olky 

17 February 2011 - 01:06 AM
Exercise 6 Password Checker
Write a program that repeatedly asks the user for a proposed password until the user enters an acceptable password. When the user enters an acceptable password, the program writes a message and exits.
Acceptable passwords:
1. Are at least 7 characters long.
2. Contain both upper and lower case alphabetic characters.
3. Contain at least 1 digit.
The logic of this program can be quite tricky. Hint: use toUpperCase(), toLowerCase, and equals(). You will also need nested ifs.
Here is a run of the program:
Enter your password:
snowflake
That password is not acceptable.

Enter your password:
SnowFlake
That password is not acceptable.

Enter your password:
snowflake47
That password is not acceptable.

Enter your password:
Snowflake47
Acceptable password.
0
Page 1 of 1

December 2020

S M T W T F S
  1234 5
6789101112
13141516171819
20212223242526
2728293031  

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)