gxmad
gxmad

Reputation: 2230

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

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

Upvotes: 5

Views: 12786

Answers (3)

Potis23
Potis23

Reputation: 522

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

Upvotes: 0

andrei d.
andrei d.

Reputation: 21

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

Upvotes: 2

Viktor
Viktor

Reputation: 237

You can try and refer :

from Crypto.PublicKey import RSA
from Crypto.Cipher import HS256

def encrypt_text(input_text):
   utf8_text = input_text.encode('utf-8')
   pub_key = RSA.importKey(open(settings.RSA).read())
   cipher = HS256.new(public_key)
   cipher_text = base64.encodebytes(cipher.encrypt(utf8_text))
   return cipher_text.decode('utf-8')

Create Public and private key :

ssh-keygen -t rsa -C "[email protected]"

Hope helpful

Upvotes: 2

Related Questions