generate_password 2.2 KB
Newer Older
C
custa 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#!/usr/bin/env python3
"""
command line to generate password hash by pbkdf2
"""

import sys
import re
from werkzeug.security import generate_password_hash


def password_strength_check(password):
    """
    Verify the strength of 'password'
    Returns a dict indicating the wrong criteria
    """

    # calculating the length
    length_error = len(password) < 6

    # 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"[~!@#%^*_+=-]", password) is None

    # overall result
    password_ok = not (length_error or digit_error or uppercase_error or lowercase_error or symbol_error)

    return {
        'ok': password_ok,
        'error': {
            'length': length_error,
            'digit': digit_error,
            'uppercase': uppercase_error,
            'lowercase': lowercase_error,
            'symbol': symbol_error,
        }
    }


47 48
def usage():
    """ usage """
C
custa 已提交
49
    print(
50 51 52 53 54 55
        """usage:
    generate_password PASSWORD

PASSWORD must be within the latin1 character set

PASSWORD strength require:
C
custa 已提交
56 57 58 59 60 61 62
    6 characters or more
    at least 1 digit [0-9]
    at least 1 alphabet [a-z]
    at least 1 alphabet of Upper Case [A-Z]
    at least 1 special character from [~!@#%^*_+=-]
"""
    )
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95


def latin1_encode(text):
    """ latin1 encode """
    try:
        text.encode("latin1")
    except UnicodeEncodeError as err:
        return str(err)
    return None


if __name__ == "__main__":
    if len(sys.argv) != 2:
        usage()
        sys.exit(1)

    password_ = sys.argv[1]
    err = latin1_encode(password_)
    if err:
        print("password: outside the 'latin-1' character set range")
        sys.exit(1)

    ret = password_strength_check(password_)
    if not ret['ok']:
        usage()

        print("Password strength is not satisfied:")
        for item in ret['error']:
            if ret['error'][item]:
                print("{} not satisfied.".format(item))
        sys.exit(1)
    else:
        print(generate_password_hash(password_))