在python中生成密码 [英] Generate password in python

查看:95
本文介绍了在python中生成密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中生成一些字母数字密码.一些可能的方法是:

I'dl like to generate some alphanumeric passwords in python. Some possible ways are:

import string
from random import sample, choice
chars = string.letters + string.digits
length = 8
''.join(sample(chars,length)) # way 1
''.join([choice(chars) for i in range(length)]) # way 2

但我不喜欢两者,因为:

But I don't like both because:

  • 方式1 仅选择了唯一字符,并且您不能生成长度> len(字符)的密码
  • 方法2 ,我们有未使用的i变量,但我找不到如何避免这种情况的好方法
  • way 1 only unique chars selected and you can't generate passwords where length > len(chars)
  • way 2 we have i variable unused and I can't find good way how to avoid that

那么,还有其他不错的选择吗?

So, any other good options?

P.S.因此,我们在这里用timeit进行了100000次迭代的测试:

P.S. So here we are with some testing with timeit for 100000 iterations:

''.join(sample(chars,length)) # way 1; 2.5 seconds
''.join([choice(chars) for i in range(length)]) # way 2; 1.8 seconds (optimizer helps?)
''.join(choice(chars) for _ in range(length)) # way 3; 1.8 seconds
''.join(choice(chars) for _ in xrange(length)) # way 4; 1.73 seconds
''.join(map(lambda x: random.choice(chars), range(length))) # way 5; 2.27 seconds

所以,胜利者是''.join(choice(chars) for _ in xrange(length)).

推荐答案

Python 3.6及更高版本

您应该使用秘密模块生成密码安全的密码,该密码是从Python 3.6开始可用.改编自文档:

Python 3.6 onwards

You should use the secrets module to generate cryptographically safe passwords, which is available starting in Python 3.6. Adapted from the documentation:

import secrets
import string
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(20)) # for a 20-character password

这篇关于在python中生成密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆