jwe cannot encrypt data correctly by jwcrypto

700 views Asked by At

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.

1

There are 1 answers

1
neal On

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)