import OpenSSL
import base64
import json
import hashlib

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymetric import padding

key = OpenSSL.crypt.PKey()
key.generate_key(type=OpenSSL.crypto.RSA,bits=2048)
priv = key.to_cryptography_key()
pub = priv.public_key()

def safe_enc(n):
    return base64.urlsafe_b64encode((n).to_bytes((n).bit_length()//8+1,byteorder='big')).decode('utf8').rstrip("=")

header = {
    "alg":"PS256",
    "jwk": {
          "kty":"RSA",
          "kid":"bilbo.baggins@hobbiton.example",
          "use":"sig",
          "n": safe_enc(pub.public_numbers().n),
          "e": safe_enc(pub.public_numbers().e)
          }
    }
payload = "YWRtaW4"

raw = base64.urlsafe_b64decode(bytes(json.dumps(header), encoding='utf-8')).decode('utf-8').rstrip("=")+"."+payload
sig = priv.sign(bytes(raw, encoding='utf8'), algorithm=hashes.SHA256(),padding=padding.PKCS1v15())

print(raw+'.'+base64.urlsafe_b64encode(sig).decode('utf8').rstrip("="))

hm = 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImZaLWpQejhfVUoyamtBRm9iUGNqN050cXl2QTZyWU1LUTdzUWFYVTJRMmsifQ.YQ.qO_wLmQSYZR4dX7n7nNFgK6QkfsK6m-RGTZCtypUSo0w8o9ym4TG3HpUdyHdzXpq8q1JxxvvKt9doBGE62DKEdDOWkxCSBr2SLAfdsuzyfj2O1Y7lj6syT9eWGtRUHPjHA4kjUHzLnc8IBle1AUChtsHXHgvNF1xhqJ598yBFdAGLtRgS1Iib_xP1irFAytO8SuQ63hNhJw7tzaGcWQ4jVcsBLvvBB9unvlf2b4Kr1n-bhizvrDnV5_hiVPm1tami7UxBUaw2vEyH8maAT5oP4smwHfy2PQPFjwd4HolK_024HRfYci0nQ8gJkEtBoLVxrauEqasdDiEi7_ag-vb3w'