无法在 rfc7515 的 3.3 节中获得相同的签名

Can not get the same signature in section 3.3 of rfc7515

rfc7515中有一个jws的例子:

BASE64URL(UTF8(JWS Protected Header)) = eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9

BASE64URL(JWS 负载)= eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ

它的秘钥是一个jwk:

{"kty":"oct", "k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow" }

然后我们需要使用 HMAC SHA-256 算法计算 JWS 签名输入 ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload)) 的 HMAC指定了密钥并对结果进行了 base64url 编码。

在jws示例中,它给出了'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'作为签名,而我得到'ZekyXWlxvuCN9H8cuDrZfaRa3pMJhHpv6QKFdUqXbLc=' .有什么问题吗?

这是我的 python3 代码。

import hashlib
import hmac
import base64

message = bytes('eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ','ascii')

secret = bytes('AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow','utf-8')

signature = base64.urlsafe_b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())

print(signature)

我发现直接用密钥字节签名是错误的。我应该使用 base64url_decode(key)。然后我得到正确的签名 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk='.

import hashlib
import hmac
import base64

message = bytes('eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ','ascii')

secret = base64.urlsafe_b64decode('AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow==')

signature = base64.urlsafe_b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())

print(signature)