如何在 python 中生成随机密码

How to generate random password in python

我想使用python3生成随机密码来加密我的文件,创建的随机密码应该有以下限制

  1. 最小长度应为 12
  2. 必须包含一个大写字母。
  3. 必须包含一个小写字母。
  4. 必须包含一位数字。
  5. 必须包含一个特殊字符。

实际上我不太了解在 python 中生成随机事物的限制,所以我没有任何代码可以在这里显示。

您可以使用 python secrets 库从列表中选择一个字符。这是一个例子:

import string
import secrets

symbols = ['*', '%', '£'] # Can add more

password = ""
for _ in range(9):
    password += secrets.choice(string.ascii_lowercase)
password += secrets.choice(string.ascii_uppercase)
password += secrets.choice(string.digits)
password += secrets.choice(symbols)
print(password)

您可以生成随机位,将它们转换为整数,限制它们,这样它就不会选择奇怪的字符并将它们转换为 char

 import random
 
  passwrd = ''
  length = 12
  for _ in range(length):
      bits = random.getrandbits(8)
      num = (int('{0:b}'.format(bits),2) + 33) % 127
      passwrd+= chr(num)

那你可以看看你的条件是否满足

我对 python 和 Whosebug 比较陌生,但这是我解决你的问题的方法:

import string
import random


def password_generator(length):
    """ Function that generates a password given a length """

    uppercase_loc = random.randint(1,4)  # random location of lowercase
    symbol_loc = random.randint(5, 6)  # random location of symbols
    lowercase_loc = random.randint(7,12)  # random location of uppercase

    password = ''  # empty string for password

    pool = string.ascii_letters + string.punctuation  # the selection of characters used

    for i in range(length):

        if i == uppercase_loc:   # this is to ensure there is at least one uppercase
            password += random.choice(string.ascii_uppercase)

        elif i == lowercase_loc:  # this is to ensure there is at least one uppercase
            password += random.choice(string.ascii_lowercase)

        elif i == symbol_loc:  # this is to ensure there is at least one symbol
            password += random.choice(string.punctuation)

        else:  # adds a random character from pool
            password += random.choice(pool)

    return password  # returns the string

print(password_generator(12))

我导入了两个模块,一个是 'string',它使我能够访问包含我需要的所有字符的字符串。另一个是 'random',它允许我生成随机数并从字符串中选择一个随机字符。

使用 random.randint(a, b) 我可以为大写字母、小写字母和标点符号生成随机位置,以确保每个字符至少有一个。

我做的唯一修改是,我做了一个你可以生成任意长度的密码,只要你在函数中输入所述长度。

这是一个输出示例: L"mJ{~xcL[%M

下面的代码完全按照我的要求执行,但我将@OliverF 代码标记为解决此问题的方法,因为他的代码也能正常工作并在我自己的答案之前发布。

#!/usr/bin/env python3
#import the necessary modules!
import random
import string

length = random.randint(12,25)
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
    
all = lower + upper + num + symbols

temp = random.sample(all,length)

password = "".join(temp)

print(password)