5

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

gxmad
  • 1,650
  • 4
  • 23
  • 29

3 Answers3

2

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 "your_email@example.com"

Hope helpful

Viktor
  • 237
  • 1
  • 2
  • 1
    Hello Viktor, thanks for the answer, I already have a key, why do you use utf-8? i need it in base64 – gxmad Jul 26 '17 at 08:07
  • 1
    It belong to your data which you want to encrypt, I use this for encrypt my user and password – Viktor Jul 27 '17 at 09:29
  • @BELLOULGAYA Because he is encoding text (String) to bytes, hence UTF-8. See [this](https://stackoverflow.com/questions/6792003/utf-8-encoding-vs-base-64-encoding?rq=1) for UTF-8 and Base64 usage. – CᴴᴀZ Jul 26 '18 at 09:48
2

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

Community
  • 1
  • 1
andrei d.
  • 21
  • 2
0

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

panos
  • 328
  • 1
  • 4
  • 16
  • 1
    Link-only answers are not really appreciated on StackOverflow. Can you write a brief summary saying why you think PyJWT might solve the problem? – joanis Oct 22 '21 at 13:26