Sample code for 30+ languages & platforms
Zig

Decrypt a JWE with a Private Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPrivateKey, which sets the private key used to decrypt a recipient of a loaded JWE.

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. The private key unwraps the content-encryption key that was wrapped with the corresponding public key during encryption.

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();

    const jwe = try chilkat.Jwe.init();
    defer jwe.deinit();

    // Load the JWE compact serialization to be decrypted.
    const jwe_compact = "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0.<...>.<iv>.<ciphertext>.<tag>";
    jwe.loadJwe(jwe_compact) catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        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 private key.
    const priv_key = try chilkat.PrivateKey.init();
    defer priv_key.deinit();
    priv_key.loadPemFile("qa_data/recipient_privkey.pem") catch {
        std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
        return;
    };

    // Set the private key used to decrypt recipient 0.
    jwe.setPrivateKey(0, priv_key) catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

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

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