generate_password 2.3 KB
Newer Older
C
custa 已提交
1 2 3 4 5 6 7 8 9 10
#!/usr/bin/env python3
"""
command line to generate password hash by pbkdf2
"""

import sys
import re
from werkzeug.security import generate_password_hash


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
def usage():
    """ usage """
    print(
        """usage: generate_password PASSWORD

Requirements:
1. PASSWORD must be within the 'latin1' character set
2. PASSWORD strength require:
    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 [~!@#%^*_+=-]
"""
    )


def password_encode_check(password):
    """ check if password within the latin1 character set """
    try:
        password.encode("latin1")
    except UnicodeEncodeError as err:
        return str(err)
    return None


C
custa 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
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,
        }
    }


73 74 75
if __name__ == "__main__":
    if len(sys.argv) != 2:
        usage()
Z
Zhangyifan 已提交
76
        print("Error: One password input allowed.")
77 78 79
        sys.exit(1)

    password_ = sys.argv[1]
80 81 82

    ret = password_encode_check(password_)
    if ret:
C
chenyanpan 已提交
83
        usage()
84
        print("PASSWORD: only latin1 character set are allowed")
85 86 87 88 89 90 91 92 93 94 95 96
        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_))