2

我想使用python生成包括小写和大写以及数字的密码,但它应该保证所有这三种都已使用。到目前为止,我写了这个,但它不能保证所有 3 种字符都被使用。我想将 8 个字符分成 2 部分。第一个 3 和最后 5 个。然后确保在第一部分中使用了所有 3 种字符,然后将它们与下一部分打乱,但我不知道如何编码。

import random
a = 0
password = ''
while a < 8:
    if random.randint(0, 61) < 10:
        password += chr(random.randint(48, 57))
    elif 10<random.randint(0, 61)<36:
        password += chr(random.randint(65, 90))
    else:
        password += chr(random.randint(97, 122))
    a += 1
print(password)
4

3 回答 3

3

如您所说:前三个位置分别从大小写字符和数字中随机选择,其余位置从所有字符中随机选择,然后随机播放。

from random import choice, shuffle
from string import ascii_uppercase, ascii_lowercase, digits
pwd = [choice(ascii_lowercase), choice(ascii_uppercase), choice(digits)] \
      + [choice(ascii_lowercase + ascii_uppercase + digits) for _ in range(5)]
shuffle(pwd)
pwd = ''.join(pwd)

请注意,这种方式的数字可能有点“代表性不足”,因为它们是从所有可用字符的大部分中随机选择的,因此前三个字符之后的任何字符都有 10/62 的可能性是数字。如果您希望 1/3 的字符是数字(这可能不是一个好主意 - 见下文),您可以首先随机选择一个字符组,每个字符组有 1/3 的机会,然后一个字符构成该组:

pwd = [choice(ascii_lowercase), choice(ascii_uppercase), choice(digits)] \
      + [choice(choice([ascii_lowercase, ascii_uppercase, digits])) for _ in range(5)]

但请注意,这会降低随机性,从而降低密码的安全性——但要求三组中的每组中至少有一个也是如此。

于 2016-07-06T12:42:38.040 回答
0

您的问题由 3 个部分组成:

  1. 将 8 个字符分成 2 个部分 - 前 3 个和后 5 个 - (字符串切片)
  2. 确保在第一部分中使用了所有 3 种字符(验证密码)
  3. 打乱字符(打乱字符串)

Part1:切片字符串

这是一个很好的教程,教如何使用 python 对字符串进行切片

在您的情况下,如果您在代码末尾插入此...

print(password[:3])
print(password[3:])

...您会看到前 3 个字符和后 5 个字符。


Part2:验证密码

一个很好的答案可以在这里找到。

def password_check(password):
    # 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

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

    return password_ok

password_check(password) 

True如果满足所有条件,则此函数将返回,否则将返回False


Part3:洗牌

if password_check(password) == True:
    new_pwd = ''.join(random.sample(password,len(password)))
    print new_pwd

此代码将洗牌整个密码并将其分配给一个名为的新变量new_pwd


附言。 整个代码可以在这里找到!

于 2016-07-06T12:39:27.480 回答
0

您可以使用正则表达式并检查是否有任何字符与正则表达式匹配。

import re
string = "AaBbCc12"

if re.search('[a-z]',string)\
and re.search('[0-9]',string)\ 
and re.search('[A-Z]',string):
    print("This is a string you are looking for")
else:
    print("Nope")

这是一个相当不优雅的解决方案,但在理解和适应性方面是最快的。

于 2016-07-06T12:45:15.023 回答