Skip to main content
 首页 » 编程设计

python之哪个 Python JOSE 库支持嵌套 JWT(签名+加密)

2025年04月02日11unruledboy

我查看了 python-jose 和 jose,但似乎都不支持加密已签名的 JWT。例如,“jose”库支持单独签名和加密,无需嵌套。

我是否遗漏了什么,比如在库外嵌套 JWT 可能相当容易?如果是这样,请分享实现此目的的技巧,以便结果的格式正确。

请您参考如下方法:

jwcrypto支持嵌套的 JWS 和 JWE。

签名然后加密:

# Load your RSA pub and private keys 
pubKey = jwk.JWK().from_pyca(serializedPublicKey) 
privateKey = jwk.JWK().from_pyca(serializedPrivateKey) 
 
# your JWT claims go here 
claims = { 
    # JWT claims in JSON format 
          } 
# sign the JWT 
# specify algorithm needed for JWS 
header = { 
          u'alg' : 'RS256',  
          'customSigHeader':'customHeaderContent' 
          } 
# generate JWT 
T = jwt.JWT(header, claims) 
# sign the JWT with a private key 
T.make_signed_token(privateKey) 
# serialize it 
signed_token = T.serialize(compact=True) 
 
# JWE algorithm in the header 
eprot = { 
    'alg': "RSA-OAEP",  
    'enc': "A128CBC-HS256", 
     'customEncHeader':'customHeaderContent' 
     }    
E = jwe.JWE(signed_token, json_encode(eprot)) 
# encrypt with a public key 
E.add_recipient(pubKey)# 
# serialize it 
encrypted_signed_token = E.serialize(compact=True) 

解密和验证签名:

#Decrypt and Verify signature 
E = jwe.JWE() 
# deserialize and decrypt 
E.deserialize(encrypted_signed_token, key=privateKey) 
raw_payload = E.payload 
# verify signature 
S = jws.JWS() 
S.deserialize(raw_payload, key=pubKey) 
final_payload = S.payload