【问题标题】:Django 1.7 md5cryptDjango 1.7 md5crypt
【发布时间】:2026-01-17 02:00:02
【问题描述】:

我对 django 场景仍然很陌生,仍在学习基础知识,并且会就如何解决这个问题提出一些建议。

我的任务是将 django 网站从 1.3 升级到 1.7 并将应用程序从 1.3 转移到 1.7,我能够创建一个测试项目,使用默认身份验证对管理页面进行身份验证,但是当我查看 auth_user 1.3 版本表我注意到验证是在 md5_crypt 中以以下格式(md5crypt$salt$hash)完成的,我尝试使用 passlib 1.6.2 无济于事,在数据库密码字段中将 md5crypt 更改为 md5_crypt。

有人能给我指出如何将 md5crypt 密码功能添加到默认配置的 django 1.7 项目的正确方向吗?

【问题讨论】:

  • 1.3项目如何使用md5crypt? 1.3项目中PASSWORD_HASHERS设置是什么?

标签: django authentication md5


【解决方案1】:

我似乎已经解决了这个问题,我在我们的 django 1.3 机器中找到了一个要在 md5crypt 中加密的模块,然后转到我的 django /usr/local/lib/python2.7/dist-packages/django/contrib/auth/ hashers.py 文件并定义了一个新的哈希类:

#imported md5crypt.py module that I moved to /usr/local/lib/python2.7/dist-packages/django/contrib/auth/
from django.contrib.auth import md5crypt

class MD5CryptPasswordHasher(BasePasswordHasher):
"""
The Salted MD5crypt password hashing algorithm
"""
algorithm = "md5crypt"

def encode(self, password, salt):
    assert password is not None
    assert salt and '$' not in salt
    cryptedpassword = md5crypt.md5crypt(force_bytes(password), force_bytes(salt))
    cryptedpassword = cryptedpassword.split('$',2)[2]
    #change from $1$ to md5crypt$
    return "%s$%s" % (self.algorithm, cryptedpassword)

def verify(self, password, encoded):
    algorithm, salt, hash = encoded.split('$', 2)
    assert algorithm == self.algorithm
    encoded_2 = self.encode(password, salt)
    return constant_time_compare(encoded, encoded_2)

def safe_summary(self, encoded):
    algorithm, salt, hash = encoded.split('$', 2)
    assert algorithm == self.algorithm
    return OrderedDict([
        (_('algorithm'), algorithm),
        (_('salt'), mask_hash(salt, show=2)),
        (_('hash'), mask_hash(hash)),
    ])

我的密码哈希器 settings.py:

PASSWORD_HASHERS=(
 'django.contrib.auth.hashers.MD5CryptPasswordHasher',
 '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.UnsaltedMD5PasswordHasher',
 'django.contrib.auth.hashers.CryptPasswordHasher',
)

出于安全原因,我无法与您共享模块 md5crypt.py,因为我没有此权限。

【讨论】: