【问题标题】:Python3: replace md5 by hashlibPython3:用 hashlib 替换 md5
【发布时间】:2017-05-11 08:57:26
【问题描述】:

我正在尝试将事件 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 返回一个错误,指出登录名或密码不正确。但是,我检查了两者,没关系。那你能告诉我我的代码有什么问题吗?

【问题讨论】:

    标签: python-3.x md5 hashlib


    【解决方案1】:

    这是您在发布之前真正应该尝试的事情:

    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 是正确的,而登录确实是错误的。

    【讨论】:

      【解决方案2】:

      您的代码是正确的。 如果在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
      

      【讨论】:

      • 最好重写答案中的代码,包括您的更改
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多