Django make_password对于批量创建用户过程太慢

12

我需要在Django中以编程方式创建数百(可能数千)个用户。我正在使用类似以下的代码:

from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
for username, email, pwd in big_user_list:
    m = User(username=username, email=email, password=make_password(pwd))
    m.save()

执行时间太长了。通过运行不带密码的上述脚本,我已确认make_password是罪魁祸首。

有没有什么方法可以解决这个缓慢问题,我真的需要这个脚本快速执行。


您可以按照此处的文档,将盐和自己的哈希算法传递给 make_password - Joseph Victor Zammit
1个回答

18
你可以使用 django.contrib.auth.hashers.MD5PasswordHasher 作为初始密码。根据 Django 存储密码的相关文档

By default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST. This should be sufficient for most users: it’s quite secure, requiring massive amounts of computing time to break.

[...]

Django chooses the an algorithm by consulting the PASSWORD_HASHERS setting. This is a list of hashing algorithm classes that this Django installation supports. The first entry in this list (that is, settings.PASSWORD_HASHERS[0]) will be used [by default] to store passwords, and all the other entries are valid hashers that can be used to check existing passwords. [...]

The default for PASSWORD_HASHERS is:

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher'
)
因此,您希望将默认值保持不变,但在开头使用较弱的哈希函数;确保列表中存在MD5PasswordHasher,然后使用。
make_password(pwd, None, 'md5')

为了生成一个简单的加盐MD5初始密码; 只要初始密码足够随机,这样做不会太弱。当用户更改密码时,他们的密码将使用更强的算法进行加密。

1
好主意!但是仅当您提供的初始密码确实是一个非常好的密码时 - 例如,一个完全随机的12个字符的ASCII字符串。 - nealmcb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接