简体   繁体   中英

How to encrypt dictionary data?

I am using jwcrypto to encrypt data using public key. I have gone through the documentation and the JWE class only takes plaintext as payload.

But I have a dictionary to encrypt as a payload.

I can convert the dictionary to json and encrypt the payload but the one who decrypt my data will be expecting dictionary after decription.

Is there anyway I can encrypt dictionary as payload.

JWE defines a JSON-friendly way to encrypt arbitrary data.

So what you want (encrypt a python dictionary, which maps to a JSON object) is not a JWE but actually a JWT token. A JWT is basically using the JWS and JWE standards to sign and/or encrypt a JSON object.

Just use the JWT part of jwcrypto doc: https://jwcrypto.readthedocs.io/en/latest/jwt.html

Should be something like that:

from jwcrypto.jwt import JWT
from jwcrypto.jwk import JWK
claims = {"my": "claims"} # your claims as a Python dict, that can be JSON-encoded
key = JWK.generate(kty='EC').public() # this generates an EC key, you must replace that with your recipient public key
jwt = JWT(header={"alg": "ECDH-ES+A128KW", "enc": "A256CBC-HS512"}, claims=claims) # set your own alg here according to your needs
jwt.make_encrypted_token(key)
serialized_jwt = token.serialize()

Then the deserialization must be done with a library assuming that the token is a JWT otherwise you indeed end up with a string representation of the JSON payload, that you will have to decode yourself to a Python dict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM