1
votes

In rfc7515, there is a jws example:

BASE64URL(UTF8(JWS Protected Header)) = eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9

BASE64URL(JWS Payload) = eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ

Its secret key is a jwk:

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

Then we need to compute the HMAC of the JWS Signing Input ASCII(BASE64URL(UTF8(JWS Protected Header)) || ’.’ || BASE64URL(JWS Payload)) with the HMAC SHA-256 algorithm using the key specified and base64url-encoding the result.

In the jws example, it gives 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' as the signature, while i get 'ZekyXWlxvuCN9H8cuDrZfaRa3pMJhHpv6QKFdUqXbLc='. Is there anything wrong?

Here is my python3 code.

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)

1

1 Answers

2
votes

I find it's wrong to sign with bytes of the key directly. I should use base64url_decode(key). Then I get the right signature '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)