【问题标题】:Getting incorrect HMAC SHA256 signature compared to example JWT与示例 JWT 相比,获得不正确的 HMAC SHA256 签名
【发布时间】:2020-07-03 14:22:47
【问题描述】:

我正在尝试遵循 [RFC for JSON Web Signatures]1,但在遵循示例时遇到了一些问题。

直到最后,我都无法生成相同的签名。以下是 Python 3.8 代码示例:

import hmac
import hashlib
import base64
signing_input = b"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
key = b"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
signature = hmac.digest(key, signing_input, digest=hashlib.sha256)

print(base64.urlsafe_b64encode(signature))
# Output: b'ZekyXWlxvuCN9H8cuDrZfaRa3pMJhHpv6QKFdUqXbLc='
# Expected: b'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'

此外,我尝试了一些处理 HMAC-SHA256 的在线工具,但我得到的输出与我的 Python 脚本提供的输出相同。关于我哪里出错的任何想法? [1]:https://www.rfc-editor.org/rfc/rfc7515#appendix-A.1

【问题讨论】:

    标签: python jwt hmac


    【解决方案1】:

    您使用了错误的密钥。 RFC 使用JSON Web Algorithm "oct"JSON Web Key 格式显示密钥。这意味着密钥是一个 base64url 编码的字节序列。如果您希望结果匹配,则需要在使用前对其进行解码。

    注意python的urlsafe_b64decodeurlsafe_b64encode并没有完全实现JWT和朋友使用的base64url编码。 python函数期望/产生填充字符,JWT使用的base64url编码应该被删除。

    把这一切放在一起:

    import hmac
    import hashlib
    import base64
    
    signing_input = b"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
    key = b"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
    
    # Decode the key.  Pad it with '=' characters to a length divisible by 4 
    # as expected by urlsafe_b64decode
    if len(key) % 4 == 2:
        key += b'=='
    elif len(key) % 4 == 3:
        key += b'='
    
    key = base64.urlsafe_b64decode(key)
    
    signature = hmac.digest(key, signing_input, digest=hashlib.sha256)
    signature = base64.urlsafe_b64encode(signature)
    
    # Strip off any '=' characters urlsafe_b64encode added to pad the key to
    # a length divisible by 4
    signature = signature.rstrip(b'=')
    print(signature)
    # Prints: b'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
    

    【讨论】:

    • 谢谢!我被困在这里很长一段时间。我已接受您的回答作为解决方案,但由于帐户限制无法投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多