JWT encrypting payload in python? (JWE)

微笑、不失礼 提交于 2019-12-10 13:02:24

问题


According to RFC 7516 it should be possible to encrypt the payload/claim, called JWE.

Are there any python libraries out there that support that?

I've checked PyJWT, python-jose and jwcrypto but they all just have examples for signing with HS256 (JWS).

Sorry if this is totally obvious, but when it comes to things involving crypto I'm extra cautious.


回答1:


Both Jose and jwcrypto libraries can do JWE.

For jose:

claims = {
'iss': 'http://www.example.com',
'sub': 42,
}
pubKey = {'k':\
           '-----BEGIN PUBLIC KEY-----\n\
-----END PUBLIC KEY-----'
    }
# decrypt on the other end using the private key
privKey = {'k': 
    '-----BEGIN RSA PRIVATE KEY-----\n'+\
'-----END RSA PRIVATE KEY-----'
}

encJwt = jose.encrypt(claims, pubKey)
serJwt = jose.serialize_compact(encJwt)
decJwt = jose.decrypt(jose.deserialize_compact(serJwt), privKey)

For jwcrypto:

# algorithm to use
eprot = {'alg': "RSA-OAEP", 'enc': "A128CBC-HS256"}
stringPayload = u'attack at dawn'
E = jwe.JWE(stringPayload, json_encode(eprot))
E.add_recipient(pubKey)
encrypted_token = E.serialize(compact=True)
E = jwe.JWE()
E.deserialize(encrypted_token, key=privKey)
decrypted_payload = E.payload



回答2:


https://jwcrypto.readthedocs.io/en/latest/jwk.html#examples

from jwcrypto import jwk
_k = jwk.JWK.generate(kty='RSA', size=2048)
_text = _k.export()

import json
# loading the key back
_import_key_dict = json.loads(_text)
key = jwk.JWK(**json.loads(_import_key_dict))



来源:https://stackoverflow.com/questions/39163000/jwt-encrypting-payload-in-python-jwe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!