Zig
Zig
Decrypt a JWE into a StringBuilder
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.DecryptSb, which decrypts a recipient of a loaded JWE and writes the plaintext into a StringBuilder.
Background. The recipient index selects which recipient's key material to use. The key for that recipient must be provided before decrypting.
Chilkat Zig Downloads
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 256-bit key-wrapping key (base64) for recipient index 0. In production, obtain the key
// from a secure source rather than hard-coding it.
const base64_key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
jwe.setWrappingKey(0, base64_key, "base64") catch {
std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
return;
};
// Decrypt recipient index 0, writing the plaintext into a StringBuilder.
const sb_content = try chilkat.StringBuilder.init();
defer sb_content.deinit();
jwe.decryptSb(0, "utf-8", sb_content) catch {
std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{try sb_content.getAsString(alloc)});
}