【问题标题】:Generating password using Python [closed]使用 Python 生成密码 [关闭]
【发布时间】:2021-04-06 01:54:22
【问题描述】:

我编写了一个 Python 程序来生成密码。有一个小故障,因为它没有正确洗牌。请建议一些方法来做到这一点。还建议更好的方法。

import random 
import array

digits = ['0','1','2','3','4','5','6','7','8','9']
lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
uppercase = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
Symbols = ['!','@','#','$','%','*','&']

mixture = digits + lowercase + uppercase + Symbols

random_digit = random.choice(digits)
random_lowercase = random.choice(lowercase)
random_uppercase = random.choice(uppercase)
random_symbol = random.choice(Symbols) 

Password = random_digit + random_lowercase + random_uppercase + random_symbol

length = random.randint(8,12)

for x in range (length) :
    Password = Password + random.choice(mixture) 

print(Password)

【问题讨论】:

  • 这里有什么问题?你期望什么,你会得到什么?
  • 我运行了你的代码并生成了5uH%idWn!$aDQAT。你能解释一下这个字符串是如何不洗牌的吗?
  • 好吧,您可以执行以下操作:在 1 和 4 之间随机化,然后选择数字、大小写和符号中的任何一个并附加到您的密码中。但这是一种非常糟糕的密码方式。
  • 前 4 个字符 ..
  • @Jarvis 我认为问题可能在于它始终是数字大小写特殊模式。

标签: python arrays string random


【解决方案1】:

要生成您的原始mixture,您可以利用string 中提供的字符集。另请注意,您不需要单个字符的列表,而是单个 str 也是用于此目的的可迭代序列。

>>> from string import ascii_letters as letters
>>> from string import digits as digits
>>> symbols = '!@#$%*&'
>>> mixture = digits + letters + symbols
>>> mixture
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%*&'

然后要生成一些示例密码,您可以使用 random.choicesk 参数指定要采样的长度。

>>> import random
>>> ''.join(random.choices(mixture, k=random.randint(8,12)))
'tF6iUwki1Ir'
>>> ''.join(random.choices(mixture, k=random.randint(8,12)))
'HpPJI6@m&'
>>> ''.join(random.choices(mixture, k=random.randint(8,12)))
'$KKzoiD&'

注意random.choices 允许重复字符,如果您希望它们都是唯一的,那么random.sample 将是首选。

【讨论】:

  • 您应该为此使用secrets 而不是random特别是,应该优先使用机密而不是随机模块中的默认伪随机数生成器,该生成器旨在用于建模和模拟,而不是安全或密码学。 docs.python.org/3/library/…
  • @Cory 它正在显示模块随机没有属性“选择”。
  • @sshow 也可能有人对此进行了编程。那么,一个人的表现会比另一个人更好吗?
  • @ShubhamKumar 你用的是什么版本的 Python? random.choices 是 Python 3.6 的新手。否则可以做类似''.join(random.choice(mixture) for _ in range(random.randint(8.12)))
【解决方案2】:

我正在研究 Cory Kramer 建议的方法。

from string import ascii_letters as letters
from string import digits as digits

symbols = '!@#$%&*'

mixture = digits + letters + symbols

import random
print('' .join(random.choice(mixture) for x in range (random.randint(8,12))))

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-25
  • 1970-01-01
  • 2016-02-06
  • 2011-10-01
  • 2021-03-29
  • 2016-11-16
  • 2017-10-18
相关资源
最近更新 更多