Skip to Content
oxcrypto

JWE

Encrypt and decrypt JWE compact tokens with RFC 7518 and RFC 8037 algorithms.

from oxcrypto.exchange.x25519 import X25519
from oxcrypto.jose.jwe import JWE, JWE_ENC

recipient = X25519.X25519.generate()
token = JWE.ECDH_ES_A256KW.encrypt(b"hello", recipient.public_key(), enc=JWE_ENC.A256GCM)
assert JWE.ECDH_ES_A256KW.decrypt(token, recipient, enc=JWE_ENC.A256GCM) == b"hello"

Both alg (the selector) and enc must match the token's protected header, otherwise decryption raises InvalidTag. A failed authentication tag or key unwrap raises InvalidTag.

Content encryption (enc)

SelectorAlgorithm
A128CBC_HS256, A192CBC_HS384, A256CBC_HS512AES-CBC with HMAC-SHA-2, encrypt-then-MAC (RFC 7518 section 5.2)
A128GCM, A192GCM, A256GCMAES-GCM with a 96-bit random IV

Key management (alg)

SelectorEncryption keyDecryption key
RSA1_5RSAPublicKeyRSAPrivateKey
RSA_OAEP, RSA_OAEP_256RSAPublicKeyRSAPrivateKey
A128KW, A192KW, A256KWbytes (16, 24, 32)the same bytes
DIRbytes of the enc key sizethe same bytes
ECDH_ES, ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KWECDHPublicKey (P-256, P-384, P-521), X25519PublicKey, X448PublicKeythe matching private key
A128GCMKW, A192GCMKW, A256GCMKWbytes (16, 24, 32)the same bytes
PBES2_HS256_A128KW, PBES2_HS384_A192KW, PBES2_HS512_A256KWpassword bytesthe same password

ECDH-ES writes an ephemeral epk and derives the key with the Concat KDF from RFC 7518 section 4.6, including apu and apv from header when present. PBES2 uses a random 16-byte p2s and 600,000 PBKDF2 iterations unless header sets p2c; p2c outside 1,000 to 1,000,000 raises ValueError when encrypting and decrypting, which bounds the work an attacker-supplied token can cause. X448 is experimental, see X448.

RSA1_5

Warning

RSA1_5 (RSAES-PKCS1-v1_5) is a legacy algorithm kept for interoperability. When key decryption fails, oxcrypto continues with a random content key so that the error is the same InvalidTag as a bad tag, following RFC 7516 section 11.5. The rsa crate's PKCS#1 v1.5 decryption is not documented as constant time. Prefer RSA_OAEP_256 for new tokens.

Tests use RFC 7516 Appendix A.1-A.3 and round trips for every alg and enc pair.

Zeroization

Note

The content-encryption key, derived and unwrapped keys and the decrypted plaintext buffer are wiped when a call returns; the returned plaintext is Python bytes and is not wiped. Not covered: keys and passwords passed as Python bytes and stack copies made by the AES, HMAC, RSA and curve crates.

On this page