Encrypted JWTs (JSON Web Tokens) are used to secure the exchange of information between parties by ensuring both confidentiality and integrity. Encryption prevents unauthorized access to the payload, and integrity guarantees that the data has not been tampered with during transmission.
While encryption ensures confidentiality, it does not always guarantee that a message hasn't been tampered with. For this reason, JWTs use Authenticated Encryption algorithms to ensure both confidentiality and integrity.
The JWT specification mandates the use of Authenticated Encryption algorithms for encrypting the JWT payload. Below are the standard encryption algorithms used:
Algorithm Identifier | A128CBC-HS256 | A192CBC-HS384 | A256CBC-HS512 | A128GCM | A192GCM | A256GCM |
---|
The encryption algorithms used in JWTs are all based on symmetric key cryptography, meaning the same key is used for both encryption and decryption. While symmetric encryption is fast and efficient, some use cases may require asymmetric encryption (RSA, Elliptic Curve) or password-based keys. However, asymmetric encryption is typically not used to directly encrypt JWTs due to performance and size limitations.
Instead, asymmetric encryption is used to generate a Content Encryption Key (CEK), which is then used to encrypt the JWT payload with a fast symmetric algorithm.
Key algorithmKey = getKeyManagementAlgorithmKey(); // PublicKey, SecretKey, or Password
SecretKey contentEncryptionKey = keyManagementAlgorithm.produceEncryptionKey(algorithmKey);
byte[] ciphertext = encryptionAlgorithm.encrypt(payload, contentEncryptionKey);
The JWT specification supports several Key Management Algorithms, including RSA, Elliptic Curve, and password-based key derivation algorithms. These algorithms produce the symmetric key (CEK) that is used to encrypt the JWT payload.
By using JWE (JSON Web Encryption), you can ensure that your JWTs are both confidential and tamper-proof.