The computation of a JWE is done by the JWEBuilder object. This object requires the following services:
an algorithm manager with key encryption algorithms
an algorithm manager with content encryption algorithms
<?phpuseJose\Component\Core\AlgorithmManager;useJose\Component\Encryption\Algorithm\KeyEncryption\A256KW;useJose\Component\Encryption\Algorithm\ContentEncryption\A256CBCHS512;useJose\Component\Encryption\JWEBuilder;// The key encryption algorithm manager with the A256KW algorithm.$keyEncryptionAlgorithmManager =newAlgorithmManager([newA256KW(),]);// The content encryption algorithm manager with the A256CBC-HS256 algorithm.$contentEncryptionAlgorithmManager =newAlgorithmManager([newA256CBCHS512(),]);// We instantiate our JWE Builder.$jweBuilder =newJWEBuilder( $keyEncryptionAlgorithmManager, $contentEncryptionAlgorithmManager,);
Compression is not recommended. Please avoid its use. See RFC8725 for more information.
Now let's create our first JWE object.
useJose\Component\Core\JWK;// Our key.$jwk =newJWK(['kty'=>'oct', 'k' => 'dzI6nbW4OcNF-AtfxGAmuyz7IpHRudBI0WgGjZWgaRJt6prBn3DARXgUR8NVwKhfL43QBIU2Un3AvCGCHRgY4TbEqhOi8-i98xxmCggNjde4oaW6wkJ2NgM3Ss9SOX9zS3lcVzdCMdum-RwVJ301kbin4UtGztuzJBeg5oVN00MGxjC2xWwyI0tgXVs-zJs5WlafCuGfX1HrVkIf5bvpE0MQCSjdJpSeVao6-RSTYDajZf7T88a2eVjeW31mMAg-jzAWfUrii61T_bYPJFOXW8kkRWoa1InLRdG6bKB9wQs9-VdXZP60Q4Yuj_WZ-lO7qV9AEFrUkkjpaDgZT86w2g',
]);// The payload we want to encrypt. It MUST be a string.$payload =json_encode(['iat'=> time(),'nbf'=> time(),'exp'=> time()+3600,'iss'=>'My service','aud'=>'Your application',]);$jwe = $jweBuilder->create()// We want to create a new JWE->withPayload($payload)// We set the payload->withSharedProtectedHeader(['alg'=>'A256KW',// Key Encryption Algorithm'enc'=>'A256CBC-HS512',// Content Encryption Algorithm ])->addRecipient($jwk)// We add a recipient (a shared key or public key).->build(); // We build it
Great! If everything is fine you will get a JWE object with one recipient. We want to send it to the audience. Before that, it must be serialized.
We will use the compact serialization mode. This is the most common mode as it is URL safe and very compact. Perfect for a use in a web context!
useJose\Component\Encryption\Serializer\CompactSerializer;$serializer =newCompactSerializer(); // The serializer$token = $serializer->serialize($jwe,0); // We serialize the recipient at index 0 (we only have one recipient).
All good! The variable $token now contains a string that should be something like that: