2

我正在使用jwcrypto公钥加密数据。我已经阅读了文档,并且JWE该类仅将纯文本作为有效负载。

但是我有一本字典可以加密为有效载荷。

我可以将字典转换为 json 并加密有效负载,但解密我的数据的人会在解密后期待字典。

无论如何我可以将字典加密为有效负载。

4

1 回答 1

2

JWE 定义了一种对 JSON 友好的方式来加密任意数据。

所以你想要的(加密一个映射到 JSON 对象的 python 字典)不是 JWE,而是 JWT 令牌。JWT 基本上使用 JWS 和 JWE 标准来签署和/或加密 JSON 对象。

只需使用 jwcrypto doc 的 JWT 部分:https ://jwcrypto.readthedocs.io/en/latest/jwt.html

应该是这样的:

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()

然后必须使用库来完成反序列化,假设令牌是 JWT,否则您确实会得到 JSON 有效负载的字符串表示,您必须将自己解码为 Python dict。

于 2019-10-25T09:55:51.370 回答