Sample code for 30+ languages & platforms
Java

Encrypt a JWE with a Recipient Public Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Jwe;
import com.chilkatsoft.chilkat2.PublicKey;

public class ChilkatExample {

    public static void main(String[] args) {
        Jwe jwe = new Jwe();

        // Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
        JsonObject header = new JsonObject();
        header.updateString("alg", "RSA-OAEP-256");
        header.updateString("enc", "A256GCM");
        try {
            jwe.setProtectedHeader(header);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // The file path is relative to the application's current working directory.  An absolute path
        // may also be used.  Supply the path appropriate to your own environment.
        // Load the recipient's public key.
        PublicKey pubKey = new PublicKey();
        String jweCompact;
        try {
            pubKey.loadFromFile("qa_data/recipient_pubkey.pem");

            // Set the public key used to encrypt for recipient 0.
            jwe.setPublicKey(0, pubKey);

            jweCompact = jwe.encrypt("This is the secret content.", "utf-8");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(jweCompact);
    }
}