0

I am setting up my server and I want to have the passwords with complexity.

Using a regex in Python, how can I verify that a user's password is:

At least 8 characters

Must be restricted to, though does not specifically require any of:

uppercase letters: A-Z

lowercase letters: a-z

numbers: 0-9

any of the special characters: @#$%^&+=

import re

password = raw_input("Enter string to test: ")

if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', password):

    # match
else:

    # no match

from wtforms import StringField, PasswordField, SubmitField, BooleanField

from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError


class RegistrationForm(FlaskForm):

    username = StringField('Username',
                           validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('Email',
                        validators=[DataRequired(), Email()])
    #password = 
    pattern = "^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"
    password = PasswordField('Password', validators=[DataRequired(), Length(min=2, max=20)])
    if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', password):
        print ("Valid password")
    else:
        print ("Password not valid")

I expect the output to be valid or invalid password

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Diogo
  • 1
  • http://regexlib.com/Search.aspx?k=strong%20password&AspxAutoDetectCookieSupport=1 have you tried modifying the examples given here to fit your use case? – ycx Mar 27 '19 at 02:35
  • The first part is working in cmd line, but the second part from wtforms is where I am trying to implement in my app. So in command line is working, but in my app it is not working. – Diogo Mar 27 '19 at 02:44
  • following NIST guidlines personally I would "allow all printable ASCII characters, including spaces, and should accept all UNICODE characters, too, including emoji" and if not I'd increase minimum from 8 characters. – Andrew Allen Mar 27 '19 at 13:25
  • You might find [Reference - Password Validation](https://stackoverflow.com/q/48345922/3600709) useful. – ctwheels Mar 27 '19 at 15:17

1 Answers1

2

A regex seems a bit heavy to me. You can just use normal string operations:

from string import ascii_lowercase, digits

punctuation = '@#$%^&+='
valid_characters = ascii_lowercase + digits + punctuation

def validate_password(password):
    return len(password) >= 8 and set(password) <= set(valid_characters)
gmds
  • 19,325
  • 4
  • 32
  • 58