How to validate password strength using a regular expression

Regular expressions are as complicated as they are powerful.

By  

Source: Matt Mombrea

Password strength requirements are a hot topic as of late due to a slew of compromised sites and services exposing millions of user accounts to hackers. To no one’s surprise, the most used passwords are embarrassingly weak. “password” anyone?

The first step in a long process of securing any service with user accounts is enforcing a password policy of sufficient complexity. This can be done in a number of ways programmatically by creating the proper logic during the registration process, but that solution is specific to each scenario. A more general solution is to use RegEx (regular expressions) to define a pattern that meets your desired requirements.

Regular expressions are as complicated as they are powerful. They can be very intimidating in the beginning, so the best way to start is to take an example and tweak it until you produce exactly what you need. It also helps to list out your goals before you begin.

For this example, the rules I would like to enforce are:

  • The password length must be greater than or equal to 8

  • The password must contain one or more uppercase characters

  • The password must contain one or more lowercase characters

  • The password must contain one or more numeric values

  • The password must contain one or more special characters

Those are a lot of requirements. Amazingly, all of those requirements can be expressed in a single line of a regular expression:

(?=^.{8,}$)(?=.*\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$

Rubular Link

Granted, that single line RegEx looks like a random garble of characters at first glance. In reality, it is a carefully constructed set of rules to dictate a pattern match on a string. As a primer, have a look at the RegEx syntax guide, then load up a RegEx tester like Rubular and start playing around with different combinations until you get a feel for it.

Once you have your expression written, implementing it in the programming language of your choice is trivial as RegEx is well supported in nearly every language.

Read more of Matthew Mombrea's ByteStream blog and follow Matt on Twitter (@mombrea) and Google+. For the latest IT news, analysis and how-tos, follow ITworld on Twitter and Facebook.

Don't miss...

Why you should jailbreak your Apple TV - and how to do it
Why you should jailbreak your Apple TV - and how to do it
Apple iOS app review - frustrating and bad for your health
Apple iOS app review - frustrating and bad for your health
The best home backup plan options
The best home backup plan options
Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Ask a Question
randomness