TypeError:类型为“\RSAPrivateKey”的对象不是JSON serializab

2024-03-29 11:06:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为jwt断言解密我的私钥。当我编码它时,我得到了json序列化错误。你知道吗

我正在使用

key = serialization.load_pem_private_key(
  data=privateKey.encode('utf8'),
  password=passphrase.encode('utf8'),
  backend=default_backend()
)

但是我在使用jwt.jwt.encode编码() TypeError:类型为“\RSAPrivateKey”的对象不可JSON序列化

Full code:

import jwt
import json
import os
import time
import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

config = json.load(open('245883597_swrdgywm_config.json'))
appAuth = config["boxAppSettings"]["appAuth"]
privateKey = appAuth["privateKey"]
passphrase = appAuth["passphrase"]

# To decrypt the private key we use the cryptography library
# (https://cryptography.io/en/latest/)
key = serialization.load_pem_private_key(
data=privateKey.encode('utf8'),
password=passphrase.encode('utf8'),
backend=default_backend()
)


# We will need the authentication_url  again later,
# so it is handy to define here
authentication_url = 'https://api.box.com/oauth2/token'

claims = {
'iss': config['boxAppSettings']['clientID'],
'sub': config['enterpriseID'],
'box_sub_type': 'enterprise',
'aud': authentication_url,
 # This is an identifier that helps protect against
 # replay attacks
 'jti': binascii.hexlify(os.urandom(64)),
 #  We give the assertion a lifetime of 45 seconds 
 # before it expires
 'exp': int(round(time.time(), 0) + 45)
 }

 keyId = config['boxAppSettings']['appAuth']['publicKeyID']
 # Rather than constructing the JWT assertion manually, we are 
 # using the pyjwt library.
 assertion = jwt.JWT.encode(
 claims, 
 key, alg='RS512',
 # The API support "RS256", "RS384", and "RS512" encryption

 optional_headers={
 'kid': keyId
 }
 ) 

Tags: thekeyimportconfigbackendjsonloadserialization