Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

JWE using RSAES-PKCS1-v1_5 and AES_128_CBC_HMAC_SHA_256

See more JSON Web Encryption (JWE) Examples

This example duplicates the example A.2 in RFC 7516 for JSON Web Encryption (JWE).

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Note: This example requires Chilkat v9.5.0.66 or greater.

    const plaintext = "Live long and prosper.";

    // First build the JWE Protected Header.
    // We want to build this: {"alg":"RSA1_5","enc":"A128CBC-HS256"}
    const jwe_prot_hdr = try chilkat.JsonObject.init();
    defer jwe_prot_hdr.deinit();
    jwe_prot_hdr.appendString("alg", "RSA1_5") catch {};
    jwe_prot_hdr.appendString("enc", "A128CBC-HS256") catch {};
    std.debug.print("JWE Protected Header: {s}\n", .{try jwe_prot_hdr.emit(alloc)});
    std.debug.print("--\n", .{});

    // The specific RSA key used in the A.2 example is the following JWK:
    const sb_jwk = try chilkat.StringBuilder.init();
    defer sb_jwk.deinit();
    sb_jwk.append("{\"kty\":\"RSA\",") catch {};
    sb_jwk.append("\"n\":\"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl") catch {};
    sb_jwk.append("UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre") catch {};
    sb_jwk.append("cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_") catch {};
    sb_jwk.append("7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI") catch {};
    sb_jwk.append("Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU") catch {};
    sb_jwk.append("7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw\",") catch {};
    sb_jwk.append("\"e\":\"AQAB\",") catch {};
    sb_jwk.append("\"d\":\"VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq") catch {};
    sb_jwk.append("1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry") catch {};
    sb_jwk.append("nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_") catch {};
    sb_jwk.append("0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj") catch {};
    sb_jwk.append("-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-Kyvj") catch {};
    sb_jwk.append("T1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ\",") catch {};
    sb_jwk.append("\"p\":\"9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68") catch {};
    sb_jwk.append("ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEP") catch {};
    sb_jwk.append("krdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM\",") catch {};
    sb_jwk.append("\"q\":\"uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-y") catch {};
    sb_jwk.append("BhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN") catch {};
    sb_jwk.append("-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0\",") catch {};
    sb_jwk.append("\"dp\":\"w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuv") catch {};
    sb_jwk.append("ngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcra") catch {};
    sb_jwk.append("Hawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs\",") catch {};
    sb_jwk.append("\"dq\":\"o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff") catch {};
    sb_jwk.append("7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_") catch {};
    sb_jwk.append("odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU\",") catch {};
    sb_jwk.append("\"qi\":\"eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlC") catch {};
    sb_jwk.append("tUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZ") catch {};
    sb_jwk.append("B9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo\"") catch {};
    sb_jwk.append("}") catch {};

    // Load this JWK into a Chilkat private key object.
    const rsa_priv_key = try chilkat.PrivateKey.init();
    defer rsa_priv_key.deinit();
    rsa_priv_key.loadJwk(try sb_jwk.getAsString(alloc)) catch {
        std.debug.print("{s}\n", .{try rsa_priv_key.getLastErrorText(alloc)});
        return;
    };

    // The public key is used to encrypt (i.e. create the JWE),
    // and the private key is used to decrypt.
    // The RSA public key is simply a subset of the private key.  The RSA public key
    // is composed of the "n" and "e" members shown above.  These are also known as the
    // modulus and exponent.
    // We can simply get the public key object from the private key object
    const rsa_pub_key = try chilkat.PublicKey.init();
    defer rsa_pub_key.deinit();
    rsa_priv_key.toPublicKey(rsa_pub_key) catch {};

    // Create the JWE...
    const jwe = try chilkat.Jwe.init();
    defer jwe.deinit();
    jwe.setProtectedHeader(jwe_prot_hdr) catch {};
    jwe.setPublicKey(0, rsa_pub_key) catch {};

    const str_jwe = jwe.encrypt(alloc, plaintext, "utf-8") catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

    // Show the JWE we just created:
    std.debug.print("{s}\n", .{str_jwe});

    // Note: The RSA PKCS1_V1_5 padding uses random value, and the results
    // will be different each time.  However, each result should be successfully
    // decrypting if using the correct RSA private key.

    // Let's decrypt the JWE that was just produced.
    // Do the following to decrypt a JWE:
    // 1) Load the JWE.
    // 2) Set the private key for decryption.
    // 3) Decrypt.
    const jwe2 = try chilkat.Jwe.init();
    defer jwe2.deinit();
    jwe2.loadJwe(str_jwe) catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    // Provide the RSA private key for decryption.
    // (The JWE was encrypted for a single recipient at index 0.)
    jwe2.setPrivateKey(0, rsa_priv_key) catch {};

    // Decrypt.
    var original_plaintext: [:0]const u8 = jwe2.decrypt(alloc, 0, "utf-8") catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("original text: \n", .{});
    std.debug.print("{s}\n", .{original_plaintext});

    // ---------------------------------------------------------------------------------
    // It should also be possible to decrypt the JWE as shown in RFC 7516, Appendix A.2.7
    // because it was produced using the same RSA key.

    const sb_jwe = try chilkat.StringBuilder.init();
    defer sb_jwe.deinit();
    sb_jwe.append("eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.") catch {};
    sb_jwe.append("UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm") catch {};
    sb_jwe.append("1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7Pc") catch {};
    sb_jwe.append("HALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIF") catch {};
    sb_jwe.append("NPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8") catch {};
    sb_jwe.append("rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv") catch {};
    sb_jwe.append("-B3oWh2TbqmScqXMR4gp_A.") catch {};
    sb_jwe.append("AxY8DCtDaGlsbGljb3RoZQ.") catch {};
    sb_jwe.append("KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.") catch {};
    sb_jwe.append("9hH0vgRfYgPnAHOd8stkvw") catch {};

    jwe2.loadJweSb(sb_jwe) catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    // Provide the RSA private key for decryption.
    jwe2.setPrivateKey(0, rsa_priv_key) catch {};

    // Decrypt.
    original_plaintext = jwe2.decrypt(alloc, 0, "utf-8") catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{original_plaintext});
}