Python3: 用hashlib替换md5

Python3: replace md5 by hashlib

我正在尝试将多事的 API 与 Python3 结合使用。在当前状态下,登录功能使用已弃用的 md5 库。因此,我想将此函数转换为 Python 3 兼容。我面临困难的是:

response = md5.new(nonce + ':'+ md5.new(password).hexdigest()).hexdigest()

我尝试转换它是

    mpwd = hashlib.md5(password.encode())
    apwd = mpwd.hexdigest()
    s = nonce+":"+apwd
    mall = hashlib.md5(s.encode())
    response = mall.hexdigest()

不幸的是,API returns 出现错误,提示登录名或密码不正确。但是,我检查了两个,都可以。那么你能告诉我我的代码有什么问题吗?

以下是您在发帖前真正应该尝试过的东西:

Python 2.7:

>>> import md5
>>> password = 'fred'
>>> nonce = '12345'
>>> md5.new(nonce + ':'+ md5.new(password).hexdigest()).hexdigest()
'496a1ca20abf5b0b12ab7f9891d04201'

Python 2.7 和 Python 3.6:

>>> import hashlib
>>> password = 'fred'
>>> nonce = '12345'
>>> mpwd = hashlib.md5(password.encode())
>>> apwd = mpwd.hexdigest()
>>> s = nonce+":"+apwd
>>> mall = hashlib.md5(s.encode())
>>> mall.hexdigest()
'496a1ca20abf5b0b12ab7f9891d04201'

如您所见,两个版本都产生相同的 md5 哈希值。所以问题不在于您的代码。它可能与您在这段代码之后使用 response 所做的事情有关。或者 API 是正确的,而登录确实是错误的。

您的代码是正确的。 如果在md5前加上hashlib,在import md5前加上"#",问题就解决了。

导入哈希库 (从文件中删除 "import md5")

def login(self, user, password):
    "Login to the Eventful API as USER with PASSWORD."
    nonce = self.call('/users/login')['nonce']
    response = hashlib.md5.new(nonce + ':'+ hashlib.md5.new(password).hexdigest()).hexdigest()

    login = self.call('/users/login', user=user, nonce=nonce,
                      response=response)
    self.user_key = login['user_key']
    self.user = user
    return user