将密码从web2py迁移到Django

时间:2015-01-22 12:30:44

标签: django passwords web2py sha512

我使用SHA 512算法将密码存储在web2py中。我现在正在将模型迁移到django,因此需要一种方法来使用SHA 512以与web2py相同的方式在django中散列密码,以便我可以使用相同的密码验证旧用户。请提示某种方式。

2 个答案:

答案 0 :(得分:2)

根据这个post,用于重新创建web2py中使用的约定的Python代码段如下:

from hashlib import md5
import hmac
hmac_key = '<your secret key>'
password = 'insecure'
thehash = hmac.new(hmac_key, password).hexdigest()
print thehash

web2py使用hmac(这是您的秘密+用户密码的明文)作为最终哈希,而不仅仅是直接的MD5 / SHA哈希(取决于您的设置)。因此,您只需要在上面的示例中将MD5替换为SHA,以使您的工作正常进行。但是,只要密钥相同,您就需要在新应用程序中实现此实现,以使它们交叉兼容。

根据docs,哈希以下列格式存储:

    <algorithm>$<salt>$<hash>

因此,如果使用了盐,则将其与哈希一起存储,这样可以轻松获取盐以便在新应用程序中使用。美元符号可以很容易地解析每个值。

algo, salt, hash = password_hash.split("$")

更新:我从web2py源代码中提取了以下代码,但您需要做的是使用您为auth.settings.hmac_key设置的值更新变量hmac_key。希望当你运行时(更新hmac_key变量之后),这个散列应该匹配。

import hashlib
import hmac
from hashlib import sha512

h="sha512$b850ed44943b861b$c90901439983bce7fd512592b20d83f8e654632dee51de515773e70eabe609f62cebec64fed4df03acd54e6a627c9291e70fdf3a89996ffa796897c159e95c11"

algo,salt,hash = h.split("$")
print "crypted hash: %s"%hash

pwd = "pawan123"
##get this value from auth.settings.hmac_key
hmac_key = "" 

def get_digest(value):
    """
    Returns a hashlib digest algorithm from a string
    """
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return md5
    elif value == "sha1":
        return sha1
    elif value == "sha224":
        return sha224
    elif value == "sha256":
        return sha256
    elif value == "sha384":
        return sha384
    elif value == "sha512":
        return sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)

#hashed = simple_hash(self.password, key, salt, digest_alg)
def simple_hash(text, key='', salt='', digest_alg='md5'):
    """
    Generates hash with the given text using the specified
    digest hashing algorithm
    """
    if not digest_alg:
        raise RuntimeError("simple_hash with digest_alg=None")
    elif not isinstance(digest_alg, str):  # manual approach
        h = digest_alg(text + key + salt)
    elif digest_alg.startswith('pbkdf2'):  # latest and coolest!
        iterations, keylen, alg = digest_alg[7:-1].split(',')
        return pbkdf2_hex(text, salt, int(iterations),
                          int(keylen), get_digest(alg))
    elif key:  # use hmac
        digest_alg = get_digest(digest_alg)
        h = hmac.new(key + salt, text, digest_alg)
    else:  # compatible with third party systems
        h = get_digest(digest_alg)()
        h.update(text + salt)
    return h.hexdigest()




print "result hash:  %s"%simple_hash(pwd, hmac_key, salt, "sha512")

答案 1 :(得分:0)

我认为你最好的解决方案是编写一个auth后端,根据web2py基础对用户进行身份验证,然后让他更改或确认他的密码并构建一个新的Django auth-passwords。

密码哈希密码的漏洞概念是,如果您有权访问数据库,您或任何黑客都无法看到它们。

这是关于writing an authentication backend的Django文档。

相关问题