【问题标题】:How to set the crypto key for Python's MD5 module?如何为 Python 的 MD5 模块设置加密密钥?
【发布时间】:2009-03-30 13:11:35
【问题描述】:

以下 Perl 代码的 Python 等价物是什么?

hmac_md5_hex($login . "^" . $seq . "^" . $time . "^" . $amo . "^", $CryptoKey);

Python hashlib.md5 似乎没有采用“加密密钥”参数。它只接受 1 个参数。

【问题讨论】:

    标签: python hash md5 hmac


    【解决方案1】:

    您必须将hmac module 与 md5 或 sha 一起使用。默认情况下它使用 md5:

    In [1]: import hmac, hashlib
    In [2]: hmac.new('key', 'msg').hexdigest()
    Out[2]: '18e3548c59ad40dd03907b7aeee71d67'
    In [3]: hmac.new('key2', 'msg').hexdigest()
    Out[3]: 'a4bde113179bc2a7c6ac9ad7309ea073'
    In [4]: hmac.new('key', 'msg', hashlib.sha256).hexdigest()
    Out[4]: '2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628'
    

    您的示例可能类似于:

    hmac.new(CryptoKey, '^'.join([login, seq, time, amo]), hashlib.md5).hexdigest()
    

    【讨论】:

    • +1 用于使用 hashlib 而不是已弃用的 md5/sha 模块
    【解决方案2】:

    看看this python library documentation about hmac

    你可能想要的是:

    import hmac
    hmac_object = hmac.new(crypto_key)
    hmac_object.update('^'.join([login, seq, time, amo, ''])
    print hmac_object.hexdigest()
    

    最好使用 .update(),因为这样你就不必每次都实例化 hmac 类,如果你想要大量的十六进制摘要,它会显着提升性能消息。

    【讨论】:

      【解决方案3】:

      另一种解决方案,基于PyCrypto:

      from Crypto.Hash import HMAC
      print HMAC.new(CryptoKey, '^'.join([login, seq, time, amo, ''])).hexdigest()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-13
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        • 2016-10-15
        • 1970-01-01
        相关资源
        最近更新 更多