Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT encrypting payload in python? (JWE)

According to RFC 7516 it should be possible to encrypt the payload/claim, called JWE.

Are there any python libraries out there that support that?

I've checked PyJWT, python-jose and jwcrypto but they all just have examples for signing with HS256 (JWS).

Sorry if this is totally obvious, but when it comes to things involving crypto I'm extra cautious.

like image 232
Johnny Avatar asked Aug 26 '16 09:08

Johnny


People also ask

Can JWT payload be encrypted?

JSON Web Tokens (JWT) can be signed then encrypted to provide confidentiality of the claims. While it's technically possible to perform the operations in any order to create a nested JWT, senders should first sign the JWT, then encrypt the resulting message.

What is difference between JWT and JWE?

JSON Web Token (JWT) From the text, we can understand that JWT is not a structure but a set of claims in the shape of either JWS or JWE as its way of securing itself. In the most basic form, the difference between JWS and JWE is that everyone can see the payload of JWS while the JWE one is encrypted.

What is JWE encrypted key?

The Content Encryption Key (CEK) is encrypted with the intended recipient's key and the resulting encrypted content is recorded as a byte array, which is referred to as the JWE Encrypted Key. JWE Ciphertext. A byte array containing the Ciphertext. Encoded JWE Header. Base64url encoding of the bytes of the UTF-8 RFC ...


1 Answers

Both Jose and jwcrypto libraries can do JWE.

For jose:

claims = {
'iss': 'http://www.example.com',
'sub': 42,
}
pubKey = {'k':\
           '-----BEGIN PUBLIC KEY-----\n\
-----END PUBLIC KEY-----'
    }
# decrypt on the other end using the private key
privKey = {'k': 
    '-----BEGIN RSA PRIVATE KEY-----\n'+\
'-----END RSA PRIVATE KEY-----'
}

encJwt = jose.encrypt(claims, pubKey)
serJwt = jose.serialize_compact(encJwt)
decJwt = jose.decrypt(jose.deserialize_compact(serJwt), privKey)

For jwcrypto:

# algorithm to use
eprot = {'alg': "RSA-OAEP", 'enc': "A128CBC-HS256"}
stringPayload = u'attack at dawn'
E = jwe.JWE(stringPayload, json_encode(eprot))
E.add_recipient(pubKey)
encrypted_token = E.serialize(compact=True)
E = jwe.JWE()
E.deserialize(encrypted_token, key=privKey)
decrypted_payload = E.payload
like image 196
Yifan Wu Avatar answered Oct 14 '22 06:10

Yifan Wu