Zig
Zig
JWE using A256GCMKW
See more JSON Web Encryption (JWE) Examples
This example demonstrates creating a JCE with AES GCM key wrap.Chilkat Zig Downloads
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.
const plaintext = "My text to enrypt";
const jwe = try chilkat.Jwe.init();
defer jwe.deinit();
// First build the JWE Protected Header:
// {
// "alg": "A256GCMKW",
// "kid": "18ec08e1-bfa9-4d95-b205-2b4dd1d4321d",
// "tag": "kfPduVQ3T3H6vnewt--ksw",
// "iv": "KkYT0GX_2jHlfqN_",
// "enc": "A128CBC-HS256"
// }
const jwe_prot_hdr = try chilkat.JsonObject.init();
defer jwe_prot_hdr.deinit();
jwe_prot_hdr.appendString("alg", "A256GCMKW") catch {};
// kid is optional
jwe_prot_hdr.appendString("kid", "18ec08e1-bfa9-4d95-b205-2b4dd1d4321d") catch {};
// tag is optional
jwe_prot_hdr.appendString("tag", "kfPduVQ3T3H6vnewt--ksw") catch {};
jwe_prot_hdr.appendString("enc", "A256GCM") catch {};
// the iv should be 16 random chars.
const prng = try chilkat.Prng.init();
defer prng.deinit();
jwe_prot_hdr.appendString("iv", try prng.randomString(alloc, 16, true, true, true)) catch {};
jwe.setProtectedHeader(jwe_prot_hdr) catch {};
std.debug.print("JWE Protected Header: {s}\n", .{try jwe_prot_hdr.emit(alloc)});
std.debug.print("--\n", .{});
// Given that we have 256-bit AES, our key should be 32 bytes.
// The ascii string here is 32 bytes, therefore the 2nd arg is "ascii" to use these
// ascii chars directly as the key.
const aes_wrapping_key = "2baf4f730f5e4542b428593ef9cceb0e";
jwe.setWrappingKey(0, aes_wrapping_key, "ascii") catch {};
// Encrypt and return the JWE:
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});
// Decrypt the JWE that was just produced.
// 1) Load the JWE.
// 2) Set the AES wrapping key.
// 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;
};
// Set the AES wrap key. Important to use "ascii"
jwe2.setWrappingKey(0, aes_wrapping_key, "ascii") catch {};
// Decrypt.
const original_plaintext = 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});
}