[英]generating a valid password - Python
I have the following method to generate random passwords: 我有以下方法来生成随机密码:
char_set = {
'small': 'abcdefghijklmnopqrstuvwxyz',
'nums': '0123456789',
'big': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'special': '^!\$%&/()=?{[]}+~#-_.:,;<>|\\'
}
def gen_password(length=21):
'''
Generate a random password containing upper and lower case letters,
numbers and special characters.
Arguments:
----------
The default length is 21 chars, however the minimum is 8 chars.
Returns:
--------
str: The random password
'''
assert length >= 8
password = []
while len(password) < length:
key = random.choice(char_set.keys())
a_char = os.urandom(1)
if a_char in char_set[key]:
if check_prev_char(password, char_set[key]):
continue
else:
password.append(a_char)
return ''.join(password)
def check_prev_char(password, current_char_set):
'''
Ensure that there are not consecutive Uppercase / Lowecase / Number / special
characters in the password.
Arguments:
----------
password: (str)
The candidate password
current_char_set: (char)
The current character to be compared.
Returns:
--------
Bool: if the candidate password is good so far.
'''
index = len(password)
if index == 0:
return False
else:
prev_char = password[index - 1]
if prev_char in current_char_set:
return True
else:
return False
Although it works in most cases, there are a few cases it fails, for example, when the password has a \\
or doesn't have a number. 尽管它在大多数情况下都有效,但在少数情况下会失败,例如,当密码包含
\\
或没有数字时。 How can I ensure all the passwords I'm generating doesn't contain \\
and also always contain at least a number? 如何确保我生成的所有密码都不包含
\\
,并且始终至少包含一个数字?
If you don't want \\
in your password, remove them from the special charset (is there a reason it's there?): 如果您不想在密码中使用
\\
,请将其从特殊字符集中删除(是否存在该字符集?):
'special': '^!\$%&/()=?{[]}+~#-_.:,;<>|'
To ensure it always has a number, generate a password with n-1
characters and then add a number at a random position: 为了确保它始终有一个数字,请生成一个包含
n-1
字符的密码,然后在任意位置添加一个数字:
def gen_final_password(length=21):
password = gen_password(length - 1)
index = random.randint(0, length)
number = random.choice(char_set['nums'])
return password[:index] + number + password[index:]
But please note this may not generate a cryptographically random password, with the full expected entropy. 但是请注意,这可能不会生成具有完全预期熵的加密随机密码。 For that you would need to always use a crypto-random source and use all characters with equal likelihood.
为此,您将需要始终使用加密随机源,并以相同的可能性使用所有字符。 Right now the algorithm prefers characters from small charsets (eg it's more likely to include a
0
than a
). 现在,该算法更喜欢小字符集的字符(例如,比
a
更有可能包含0
)。 Also, avoiding consecutive characters of the same charset has unknown, bad implications to entropy. 同样,避免使用相同字符集的连续字符会对熵产生未知的不良影响。
Finally, check_prev_char
can be simplified to the expression: 最后,可以将
check_prev_char
简化为以下表达式:
len(password) and password[-1] in char_set[key]
^(?!.*\\)(?=.*\d).*$
您可以在末尾进行re.match
,以确保password
没有/
且至少有一个\\d
。
If you do not want the password you generate to contain '\\', why not just remove that character from the defined char_set you obtain characters for the password from? 如果您不希望生成的密码包含“ \\”,为什么不仅仅从定义的char_set中删除该字符,而从中获取该字符的密码呢?
As for generating the passwords that always have at least one number, you could check the generated password for a number before returning it and overwrite a random character with a random number before returning the password if a number is needed. 至于生成始终具有至少一个数字的密码,可以在返回密码之前检查生成的密码是否为数字,如果需要数字,则在返回密码之前可以使用随机数覆盖随机字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.