3

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
varad
  • 7,309
  • 20
  • 60
  • 112
  • 1
    Of course encryption expects binary data / byte arrays to encrypt. So you have to *encode* and *decode* things like dictionaries in one way or the other to create a single input plaintext message. The only thing you can do is to standardize the encoding / decoding as best as you can and Guillaume created a good answer for that. The only other option - usually not recommended - is to encrypt / decrypt each element separately. – Maarten Bodewes Oct 25 '19 at 12:09

1 Answers1

3

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 = jwt.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.

oruchkin
  • 1,145
  • 1
  • 10
  • 21
Guillaume
  • 5,497
  • 3
  • 24
  • 42