how to sign a token with RSA SHA-256, in python?

Viewed 7227

I am trying to encode a JWT with python, I need to encode it in base64, with i did. and then I have to sign it with a private key before sending to the server. actually I am blocked, when to sign it I don't know how, I am searching on the web since yesterday, I am little bit lost. here is my code.

import jwt

print ("\nStart..")

encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')

print("\nJWT : ",encoded)

try:
    decoded = jwt.decode(encoded, 'secret', algorithms=['HS256'])
except jwt.InvalidTokenError:
    print("Invalid token!!")

print("\ndecoded : ", decoded)

print("\nencodage : ")

#LOAD THE PRIVATE KEY


#SIGN THE ENCODED token

and there is the format of my key, it is an RSA private key.

-----BEGIN RSA PRIVATE KEY-----
dsjkfhsdfkshkdfhks...
-----END RSA PRIVATE KEY-----

I gave a certificate to the server crt.crt, i think i need to encrypt with my private key, and then they will be able to decrypt the message, with a key from the certificate, that is what i understood.

Thanks in advance, G. B

3 Answers

according to the JWT RFC, the algorithm type for RSA + SHA256 is "RS256", but you're using "HS256"

Have a look of:PyJWT

PyJWT is a Python library which allows you to encode and decode JSON Web Tokens (JWT). JWT is an open, industry-standard (RFC 7519) for representing claims securely between two parties

It supports several several algorithms for cryptographic signing link

You don't need to encode your secret/key

You provide your payload as a JSON object

It uses the appropriate '.' syntax

Related