How to do JWE encryption in Java?

In this tutorial, we will see how to perform JWE encryption in Java using the jose4j library.

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. Each component is base64 URL encoded and concatenated using the period operator . a single part for transmission.

To perform the encryption we will need the public key using which the encryption will be performed.

Also specify the Encryption method, like whether are we going to use Symmetric or Asymmetric encryption and using which types of keys and Encryption algorithm.

public String JWEEncrpyt(String payload) throws GeneralSecurityException, JoseException, IOException {

    RSAPublicKey rsaPubKey = loadEncryptionKeys.loadPublicKeyFromFile(publicKey);

    JsonWebEncryption jwe = new JsonWebEncryption();

    // RSA256 for key wrap
    jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.RSA1_5);

    // A256GCM for content encryption
    jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);

    // the key (from above)
    jwe.setKey(rsaPubKey);

    // whatever content you want to encrypt
    jwe.setPayload(payload);

    // Produce the JWE compact serialization, which is where the actual encryption is done.
    // The JWE compact serialization consists of five base64url encoded parts
    // combined with a dot ('.') character in the general format of
    // <header>.<encrypted key>.<initialization vector>.<ciphertext>.<authentication tag>
    String serializedJwe = jwe.getCompactSerialization();

    return serializedJwe;
}

This will load a public key and generate a JWE encryption for the specified payload (JSON data). Also see how to decrypt the encrypted data as JWE.