JWT hs512 signature slightly different from jwt.io if calculated with python

旧街凉风 提交于 2021-01-07 06:21:43

问题


So I get different signatures for the same JWT.

Header:

{
  "alg": "HS512",
  "typ": "JWT"
}

Payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

as a signing key I used "abc"

The resulting JWT from jwt.io is the following: eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.sNgS2IRq0LCvUaIzg9dCBVvmY_9KnrXDEmKTii6U4APbRMeUkU084wf3h5v4baP2WeZOyGunCTEa9wxh25IW6w

if I calculate the signature with python like this:

import hmac
import hashlib
import base64

s= b"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"

res = base64.b64encode(hmac.new(b"abc", msg=s, digestmod=hashlib.sha512).digest())

print(res)

then this is printed: b'sNgS2IRq0LCvUaIzg9dCBVvmY/9KnrXDEmKTii6U4APbRMeUkU084wf3h5v4baP2WeZOyGunCTEa9wxh25IW6w=='

Now except for the last two characters "==" and this "/" they are identical. Can someone explain to me why that is the case? Is it just the padding of the base64 and practically it doesn't matter if the two equal signs are there or not? Is that why jwt.io removes them?

EDIT: Changing the python code accoding to jps' hint does the trick:

import hmac
import hashlib
import base64

s= b"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"

res = base64.b64encode(hmac.new(b"abc", msg=s, digestmod=hashlib.sha512).digest())
x = res.decode("utf-8")
x = x.replace("+","-")
x = x.replace("/","_")
x = x.replace("=", "")
print(x)

回答1:


In your Python code you used Base64 encoding, but the JWT standard requires Base64URL encoding. The differences are that the characters "+" and "/" in Base64 encoding are replaced with "-" and "_" and that padding is omitted.

It might or might not work, depending on the receiving sides Base64URL decoder implementation. To be on the safe side, I recommend to follow the standard.



来源:https://stackoverflow.com/questions/64013743/jwt-hs512-signature-slightly-different-from-jwt-io-if-calculated-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!