Checking the strength of a password (how to check conditions)

后端 未结 4 656
日久生厌
日久生厌 2020-11-27 20:35

I am trying to create a system that requires you to enter a password. If it is all lower, upper or num then print weak, if it is two of the conditions, then it is med and if

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 21:01

    Holá
    The best approach is using regular expression search
    Here is the function I am currently using

    def password_check(password):
        """
        Verify the strength of 'password'
        Returns a dict indicating the wrong criteria
        A password is considered strong if:
            8 characters length or more
            1 digit or more
            1 symbol or more
            1 uppercase letter or more
            1 lowercase letter or more
        """
    
        # calculating the length
        length_error = len(password) < 8
    
        # searching for digits
        digit_error = re.search(r"\d", password) is None
    
        # searching for uppercase
        uppercase_error = re.search(r"[A-Z]", password) is None
    
        # searching for lowercase
        lowercase_error = re.search(r"[a-z]", password) is None
    
        # searching for symbols
        symbol_error = re.search(r"[ !#$%&'()*+,-./[\\\]^_`{|}~"+r'"]', password) is None
    
        # overall result
        password_ok = not ( length_error or digit_error or uppercase_error or lowercase_error or symbol_error )
    
        return {
            'password_ok' : password_ok,
            'length_error' : length_error,
            'digit_error' : digit_error,
            'uppercase_error' : uppercase_error,
            'lowercase_error' : lowercase_error,
            'symbol_error' : symbol_error,
        }
    

    EDIT:
    Fallowing a suggestion of Lukasz here is an update to the especial symbol condition verification

    symbol_error = re.search(r"\W", password) is None
    

提交回复
热议问题