In this tutorial, we will see how to do JWE decryption in Java using the jose4j library and convert the encrypted text to plain text.
JSON Web Encryption, or JWE for short, is a base64-encoded encrypted content formed out of JSON data structure. JWE Header, JWE Encrypted Key, and JWE Cypher text are three separate components that together represent the JWE (It can be more as well depending upon the serialization). Each component is base64 URL encoded and concatenated using the period operator .
a single part for transmission.
To decrypt the data we need to load the corresponding private key, which is the pair of public keys using which encryption was done.
Then specify the same encryption method and algorithm using which the original data was encrypted to decrypt it.
public String JWEDecrypt(String serializedJwe) throws GeneralSecurityException, JoseException, IOException { Key rsaPrivateKey = loadEncryptionKeys.loadPrivateKeyFromFile(privateKey); JsonWebEncryption jwe = new JsonWebEncryption(); // RSA256 for key unwrap jwe.setAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.PERMIT, KeyManagementAlgorithmIdentifiers.RSA1_5)); // A256GCM for content decryption jwe.setContentEncryptionAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.PERMIT, ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256)); // Set the compact serialization on new Json Web Encryption object jwe.setCompactSerialization(serializedJwe); // Symmetric encryption, like we are doing here, requires that both parties have the same key. // The key will have had to have been securely exchanged out-of-band somehow. jwe.setKey(rsaPrivateKey); // Get the message that was encrypted in the JWE. This step performs the actual decryption steps. String plaintext = jwe.getPlaintextString(); return plaintext; }
This will load the private and decrypt the encrypted data.