简体   繁体   中英

jwe cannot encrypt data correctly by jwcrypto

I has a requirement to generate encrypted data by jwe. The implementation of ruby can work correctly. But the python implementation cannot work correctly.

The ruby implementation

require 'jwe'

key =  OpenSSL::PKey::RSA.new File.read 'public.pem'
payload = {user:"admin"}.to_json
puts JWE.encrypt(payload, key, enc: 'A192GCM')

The python implementation

from jwt import jwk_from_pem
from jwcrypto import jwe,jwk
from jwcrypto.common import json_encode
import json

with open("public.pem", "rb") as f:
    key = jwk.JWK.from_pem(f.read())
key = key.public()
token = jwe.JWE(u'{user:"admin"}', json_encode({"alg":"RSA-OAEP","enc":"A192GCM"}))
token.add_recipient(key)
result = token.serialize()
result = json.loads(result)
print(result["protected"] + "." + result["encrypted_key"])

I have reffered the examples of jwcrypto. But the generated token is not correct.

fixed. I should use compact instead of appending data manually.

from jwt import jwk_from_pem
from jwcrypto import jwe,jwk
from jwcrypto.common import json_encode

with open("public.pem", "rb") as f:
    key = jwk.JWK.from_pem(f.read())
key = key.public()
token = jwe.JWE('{"user":"admin"}', json_encode({"alg":"RSA-OAEP","enc":"A192GCM"}))
token.add_recipient(key)
result = token.serialize(compact=True)
print(result)

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