How to encode private key as JSON WEB TOKEN in RS256 format using python

8.6k views Asked by At

Well I have gone through a lot of questions, and their respective answers, mostly instead of private key (which starts from -----BEGIN RSA PRIVATE KEY-----) to encode in jwt, public key was being sent (which does not begin from -----BEGIN RSA PRIVATE KEY-----). I have used pyjwt library in python to encode and get the required token which I am using to send to docusign for authorization purpose. well this is what i have tried and won't work

payload = {
    "iss": CLIENT_AUTH_ID,
    "sub": ACCOUNT_ID,
    "exp": unix,
    "aud": "account-d.docusign.com",
    "scope": "signature impersonation"
}
signed = jwt.encode(payload, private_key, algorithm='RS256')

It always return with ValueError: cannot deserialize the data, their HS256 algorithm works properly fine, but when it comes to RS256 it won't, some answer suggested to convert it to PEM format but mine is already in that format (-----BEGIN RSA PRIVATE KEY----- (code) -----END RSA PRIVATE KEY-----)

2

There are 2 answers

0
Huwaiza On BEST ANSWER

Instead of using jwt library this worked for me My imports

from jose import jws
from cryptography.hazmat.primitives import serialization as crypto_serialization

private_key_pem is path for private.pem file in which i have my private key as (-----BEGIN RSA PRIVATE KEY----- (code) -----END RSA PRIVATE KEY----- )

with open(private_key_pem, "rb") as key_file:
    private_key = crypto_serialization.load_pem_private_key(key_file.read(), password=None)

key = private_key.private_bytes(crypto_serialization.Encoding.PEM,
                                crypto_serialization.PrivateFormat.PKCS8,
                                crypto_serialization.NoEncryption())
signed = jws.sign(payload, key, algorithm='RS256')

use python-jose for RS256 algorithms in this way, will work hopefully

1
JD Brennan On

The private key passed to jwt.encode has to be a bytes literal b'"...". I suspect your code is passing a string (which is unicode not bytes in Python).