高质量、简单的随机密码生成器
问题描述
我有兴趣创建一个非常简单、高质量(加密)的随机密码生成器.有没有更好的方法来做到这一点?
I'm interested in creating a very simple, high (cryptographic) quality random password generator. Is there a better way to do this?
import os, random, string
length = 13
chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random.seed = (os.urandom(1024))
print ''.join(random.choice(chars) for i in range(length))
解决方案
密码的难点在于让它们足够强大并且仍然能够记住它们.如果密码不应该被人类记住,那么它就不是真正的密码.
The difficult thing with passwords is to make them strong enough and still be able to remember them. If the password is not meant to be remembered by a human being, then it is not really a password.
您使用 Python 的 os.urandom()
:这很好.对于任何实际目的(甚至密码学),os.urandom()
的输出与真正的 alea 没有区别.然后你将它用作 random
中的种子,这不太好:它是一个非加密 PRNG,它的输出可能会表现出一些不会在统计测量工具中注册的结构,但可能是被聪明的攻击者利用.您应该一直使用 os.urandom()
.为简单起见:选择长度为 64 的字母表,例如字母(大写和小写)、数字和两个额外的标点符号(例如+"和/").然后,对于每个密码字符,从 os.urandom()
中获取一个字节,以 64 为模减少值(这是无偏的,因为 64 除以 256)并将结果用作 chars 中的索引
数组.
You use Python's os.urandom()
: that's good. For any practical purpose (even cryptography), the output of os.urandom()
is indistinguishable from true alea. Then you use it as seed in random
, which is less good: that one is a non-cryptographic PRNG, and its output may exhibit some structure which will not register in a statistical measurement tool, but might be exploited by an intelligent attacker. You should work with os.urandom()
all along. To make things simple: choose an alphabet of length 64, e.g. letters (uppercase and lowercase), digits, and two extra punctuation characters (such as '+' and '/'). Then, for each password character, get one byte from os.urandom()
, reduce the value modulo 64 (this is unbiased because 64 divides 256) and use the result as index in your chars
array.
对于长度为 64 的字母表,每个字符的熵为 6 位(因为 26 = 64).因此,对于 13 个字符,您将获得 78 位的熵.这最终并不是在所有情况下都很强大,但已经非常强大(它可能会被以数月和数十亿美元计算的预算击败,而不仅仅是数百万).
With an alphabet of length 64, you get 6 bits of entropy per character (because 26 = 64). Thus, with 13 characters, you get 78 bits of entropy. This is not ultimately strong in all cases, but already very strong (it could be defeated with a budget which will be counted in months and billions of dollars, not mere millions).
相关文章