DEV Community

loading...
Cover image for 3 password REGEX for your next project

3 password REGEX for your next project

petroskoulianos profile image Petros Koulianos ・1 min read

Regular expressions are cryptic and hard to understand and build one from scratch.
But don't panic with those cryptic symbols, the dev community can help.
Here i am writing 3 password regular expressions to use it at your next JavaScript front end app or your next nodeJs back end application.

// PASSWORD REGEX FOR YOUR NEXT JAVASCRIPT APP

// regex for a basic password must be
// more than 8 chars 
const PASSWORD_REGEX_1=  /^[A-Za-z0-9]\w{8,}$/;

// more secure regex password must be
// more than 8 chars 
// at least one number
const PASSWORD_REGEX_2 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;

// more secure regex password must be :
// more than 8 chars  
// at least one number
// at least one special character
const PASSWORD_REGEX_3=  /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,}$/;

Enter fullscreen mode Exit fullscreen mode

You can combine all 3 regular expressions to show proper warning messages.

Great web sites to check your regular expressions :

  1. regex101
  2. regexr
  3. regextester

Discussion (17)

pic
Editor guide
Collapse
icawebdesign profile image
Ian.H • Edited

While the regex patterns will work, I'd personally strongly recommend against using such features.. for example;

P@55w0rd!

This will pass all of the above regex patterns, but would you consider it a decent password to use?

Likewise, I know it's sadly common, but there's absolutely no legitimate reason to limit the length of a password if you're storing the passwords correctly. If they're stored has hashes as they should be, the hash will generally be a constant length, regardless of the length of the password itself, so limiting it to a fixed length only compromises the potential security of the password.

Collapse
petroskoulianos profile image
Petros Koulianos Author

Thanks for your reply Ian. I totally agree with the password length issue, i will update the current regex. What other options we have to check for passwords before hashing and saving to database. Do you mean options such as password dictionaries to have a cross check ??

Collapse
icawebdesign profile image
Ian.H • Edited

It's a difficult scenario. The concrete answer I guess is purely "education".

I don't think there are any kind of "rules" we can display on a site. I would advocate the use of the likes of a password manager where you can generate completely random strings of chars and never need to concern yourself with what that is. It also allows and promotes the use of unique passwords.

For other checks, I wrote a PHP package (that's my field) that provides a simple interface to Troy Hunt's Have I Been Pwned service that provides a method of checking at least for either commonly used breached passwords, which kind of falls into your thinking of a dictionary to cross-reference.

It's a long, uphill battle unfortunately to educate the masses into password security as many have used simple and/or shared passwords across multiple sources for years, and trying to get people to change their thinking is always harder than initial adoption of something.

Long and short of these types of "password strength" indicators/requirements is they can, and often will result in a false sense of security (as my P@55w0rd! example highlights).

Although never good to read or hear (or receive notifications as I do occasionally from Troy's service) about breaches, the fact these are being made more public can only help in trying to educate people on the importance of strong passwords =)

Thread Thread
petroskoulianos profile image
Petros Koulianos Author

Thanks for your great feed back 😎😎

Thread Thread
devingoble profile image
Devin Goble

It's often frustrating when a site tries to enforce arbitrary rules. It's even more frustrating when a site isn't clear about what the rules are. There are a number of sites where I can't even create an account because their front end and back end don't agree on what is a valid password, or some poorly understood RegEx is failing.

Thread Thread
icawebdesign profile image
Ian.H

It's worse when they try to enforce rules, yet when you hit those via pasting from a password manager, it fails.

I had a local council site require the same as above, though they also restricted what special chars you could use too (makes me highly suspicious, especially when a semi-colon isn't in the 'allowed list')... so I created a random string with my password manager, yet it repeatedly failed.. I modified a few of the special chars manually to fall within their permitted list and this still failed... yet the P@55w0rd! example worked.. mind blown!

I can only assume (I couldn't be bothered to try it) is that it not only requires a certain length, that it also counted keystrokes to validate that length as you typed, so pasting failed that check.

The worst part, is it's harder to make it more complex than it is to do it right (from a dev perspective).

Collapse
athomsfere profile image
Austin French

I assume you mean limit, as in upper bound and not minimum length?

Collapse
icawebdesign profile image
Ian.H

Oh totally! Guess I should have clarified that. I'm all for there being a minimum length, but definitely no upper limit =)

Collapse
ricobrase profile image
Rico Brase

Please note, that it's a bad idea to limit the password length.
If a user wants to use a 25 character password, you should let him, since this is increasing the password security.

And there is no need to make the Regex this complicated.
Just allow any character and increase the required amount of characters. This will increase the security way better than enforcing the usage of numbers and special characters.

example regex would be
/.{12,}/
(any character allowed, at least 12 characters),

Collapse
petroskoulianos profile image
Petros Koulianos Author

Thanks for your reply Rico. I have just update the password max limit length.
Why do you propose no complex passwords ??
My bank wants complex password but google not both companies want security but asks different things . What is the best approach ...

Collapse
slavius profile image
Slavius • Edited

The best approach is to pick a password that is hard to guess and at the same time complex enough not to be cracked within timespan of following years, after which it will become obsolete (you change it or stop using the service).

Using something obvious and related is really a bad idea to start with (birth dates, favorite things, names, family members, colors, songs, etc.) The best password is totally unrelated to anything known to you from the outside. This prevents password guessing by visiting your social app profiles and trying your dog's name, friends names, mother's birthdate, rock band name from your t-shirt picture and similar.

Very good rule of thumb is a sentence that makes visual sense in your head but is composed of random, totally unrelated words.

You cannot protect yourself against passwords that are improperly treated by the remote service, so any small or new service should be considered insecure and you should change passwords regularly. If someone steals unencrypted or weakly encrypted password directly from the database of that service there's nothing you can do and even the strongest password in the world will not help.

You have to take into account that efficiency and speed of password cracking increases every year (new and more powerfull GPUs, ASIC chips, new algorithms, etc.)

If your password stolen from remote service was properly encrypted and does not suffer from dictionary attack weakness (words included are not 100% included in frequently used dictionaries) then its biggest strength is its complexity.
This can be easily calulated as : entropy size ^ password length
Where entropy size is how many bits are there in each password character. E.g. only lowercase letters produce 26 possible distinct values a-z. If you add UPPERCASE letters than one character can be 26 + 26. Add digits and it will become 26 + 26 + 10 (a-z + A-Z + 0-9).
Then make this an exponent of the password length - e.g. lower + upper + digits (62) ^ password length (5) = 916,132,832. So there's about 916 million possible combinations of lower, upper and digit characters in a 5 character long password. Depending on the cryptographic algorithm used this can be enough or not. For NTLM encryption (used in Windows systems) by buying 2x NVIDIA GTX 1080 you are able to achieve 44.4 GH/s (giga [billion] hashes per second) so your 5 letter password would be cracked in an instant.
For example going to 6 characters it would take about 1s, 7 characters 79 seconds, 8 characters 81 minutes, 9 characters 84 hours and 10 characters 218 days.
Of course current RTX 3090 cards are much more effective so when the attacker has access to expensive equipment the longer your password is the longer it will take to crack it.
Please also note that:
8 character password consisting of lowercase + UPPERCASE + digits [0-9] + 16 special characters (like *-+/.,!?$#@%^& and similar) has LESS ENTROPY THAN a solely lowercase character password of length 11 characters, because:

(26+26+10+16) ^ 8 = 1,370,114,370,683,136
but:      26 ^ 11 = 3,670,344,486,987,776
Enter fullscreen mode Exit fullscreen mode
Thread Thread
petroskoulianos profile image
Petros Koulianos Author

Thanks for your reply Slavius 😎 . Υou were completely understandable 😁😁

Collapse
ricobrase profile image
Rico Brase

Well. There are different types of attacks.
Others have provided sufficient details, but I feel obliged to answer your questions (I don't want others to do ALL the work. ;-) )

Dictionary attacks:

The attacker has a list of possible words (e.g. from a dictionary of common words, hence the name) like "password", "helloworld", "sugar", or "development", which they will try on a users account. Complex passwords can provide better security, since the attacker would need "sugar" as well as different varieties (e.g. "5ug4r") of a word in his dictionary. Note, that common substitutions (e.g. a 5 for a s, a 4 for an a) might already be included in such dictionary attacks.

"regular" bruteforce:

The attacker generates a possible password (either randomly or following a scheme, e.g. "aaaa", "aaab", "aaac", etc.). Here, a complex password just won't necessarily result in a security increase, it heavily depends on the attack itself. If the attacker tries all lowercase combinations before trying combinations with uppercase letters, numbers and special characters, an all lowercase password of low length (less than 15 characters) WILL be definitely less secure than a more complex password of the same length.
If the plattform hosting the user account RESTRICTS the users from using uppercase letters, numbers and special characters for their passwords, the attacker can remove these combinations from his attack, heavily reducing the amount of guesses (and therefore the needed time) to crack the users password.


Best practise - User POV

As a user, the best way to handle passwords would be either to

1) Use a password safe and use a unique, randomly generated password with sufficient length (at least 20 characters!) with maximum complexity for each service

or

2) Use a password-less authentication method like WebAuthn.

Best practise - Developer POV

As a developer, you should provide this on your platform for maximum security:

1) Enforce passwords of maximum entropy (complexity AND length).
1a) Since it's unrealistic, users would all conform to User POV 1 (password manager with generated, safe passwords), you should at least enforce LONG passwords. Chaining known words is at least more memorable for the user and will potentially provide more secure passwords due to increased length (using 4-5 words might already result in passwords with at least 20 characters).

2) Provide standardized password-less authentication methods like WebAuthn (usage according to caniuse.com: 86% globally). Using a Public/Private-Key authentication, your users will be better protected against other types of attacks, not mentioned here, e.g. phishing (getting the users passwords by leading your users to a malicious site, designed to look indistinguishable from your site).

Collapse
kallmanation profile image
Nathan Kallman • Edited

Please never "validate" passwords with a regex; requirements like having a "special" character weaken the password space (as rules on password formation are added, fewer passwords are available, making passwords easier to guess as there are fewer to go through).

Looking at lists of common passwords (like this) very few go beyond 10 characters. So the best way to get a user to choose a secure password that they haven't used elsewhere? Make the minimum length longer than 10 characters (12 to 16 currently seems like good choices).

Even better, actually calculate the entropy of the password and require a minimum entropy for the password to be valid:

Collapse
petroskoulianos profile image
Petros Koulianos Author

Thanks for your great reply Nathan 😎. From all the great replies, for me the bottom line is that we are not safer with these rules and as a web developer we have to adopt to newer strategies such as measuring the entropy of a string rather to stay with regex.

Collapse
andrewbridge profile image
Andrew Bridge • Edited

Others have provided far more detail as to why these regex patterns enforce potentially harmful requirements.

All I can add is the ever relevant xkcd on password strength and point out that your regex patterns would disallow the suggested correcthorsebatterystaple but allow the less memorable, more brute forceable Tr0ub4dor&3.

From previous comments it also sounds as though there was previously a max length set, and that kind of thing reduces the entropy of both the suggested password above and the types of passwords created by a password manager.

Collapse
petroskoulianos profile image
Petros Koulianos Author

Thanks for your reply Andew 😎 . The sketch is very funny and absolutely true. A user can easy pass the requirements and finally give a P@ssw0rd that are easy to hack.