githubEdit

Encrypted Tokens (JWE)

Encrypt a Token with RSA-OAEP

RSA-OAEP is widely supported. The sender encrypts with the recipient's public key; only the recipient can decrypt with their private key.

<?php

use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Encryption\Algorithm\ContentEncryption\A256GCM;
use Jose\Component\Encryption\Algorithm\KeyEncryption\RSAOAEP256;
use Jose\Component\Encryption\JWEBuilder;
use Jose\Component\Encryption\Serializer\CompactSerializer;
use Jose\Component\KeyManagement\JWKFactory;

require_once 'vendor/autoload.php';

// Generate an RSA key pair (2048-bit minimum)
$privateKey = JWKFactory::createRSAKey(2048, ['alg' => 'RSA-OAEP-256', 'use' => 'enc']);
$publicKey = $privateKey->toPublic();

$algorithmManager = new AlgorithmManager([
    new RSAOAEP256(),
    new A256GCM(),
]);
$jweBuilder = new JWEBuilder($algorithmManager);

$payload = json_encode([
    'iss' => 'https://auth.example.com',
    'sub' => 'user-42',
    'iat' => time(),
    'exp' => time() + 3600,
    'email' => '[email protected]',
]);

$jwe = $jweBuilder
    ->create()
    ->withPayload($payload)
    ->withSharedProtectedHeader([
        'alg' => 'RSA-OAEP-256',
        'enc' => 'A256GCM',
    ])
    ->addRecipient($publicKey)
    ->build();

$token = (new CompactSerializer())->serialize($jwe, 0);

Decrypt the Token


Encrypt a Token with ECDH-ES (Elliptic Curve)

ECDH-ES performs a key agreement directly, producing smaller tokens than RSA.

Decrypt the Token


Encrypt a Token with a Password (PBES2)

Password-based encryption is useful when sharing tokens with users who only have a passphrase.

circle-exclamation

Decrypt with the Same Password


Encrypt a Token with a Shared Key (A256KW)

AES Key Wrap uses a symmetric key, useful for server-to-server communication.

circle-exclamation

The JWELoader combines deserialization, header checking, and decryption in a single step.

circle-info

After decryption, you should also validate the claims (exp, iss, aud, etc.) contained in the payload. See the Claim and Header Validation page.

Last updated

Was this helpful?