Zig
Zig
JWE with Binary Data
See more JSON Web Encryption (JWE) Examples
Demonstrates how to create a JWE that contains a binary payload (such as a JPG image).Note: This example requires Chilkat v9.5.0.66 or greater.
Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
var success: bool = false;
// 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.
// Load a JPG file that will be the JWE payload.
const jpg_bytes = try chilkat.BinData.init();
defer jpg_bytes.deinit();
success = if (jpg_bytes.loadFile("qa_data/jpg/starfish.jpg")) true else |_| false;
// Make sure your app checks the success/failure of the call to LoadFile..
std.debug.print("Original JPG size = {d}\n", .{jpg_bytes.getNumBytes()});
const jwe = try chilkat.Jwe.init();
defer jwe.deinit();
const jwe_prot_hdr = try chilkat.JsonObject.init();
defer jwe_prot_hdr.deinit();
jwe_prot_hdr.appendString("alg", "A128KW") catch {};
jwe_prot_hdr.appendString("enc", "A128CBC-HS256") catch {};
jwe.setProtectedHeader(jwe_prot_hdr) catch {};
const aes_wrapping_key = "GawgguFyGrWKav7AX4VKUg";
jwe.setWrappingKey(0, aes_wrapping_key, "base64url") catch {};
// Encrypt and return the JWE in sbJwe:
const sb_jwe = try chilkat.StringBuilder.init();
defer sb_jwe.deinit();
success = if (jwe.encryptBd(jpg_bytes, sb_jwe)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
return;
}
// Show the JWE:
std.debug.print("{s}\n", .{try sb_jwe.getAsString(alloc)});
std.debug.print("size of JWE: {d}\n", .{sb_jwe.getLength()});
// ---------------------------------------------------------
// Decrypt to get the original JPG file..
const jwe2 = try chilkat.Jwe.init();
defer jwe2.deinit();
success = if (jwe2.loadJweSb(sb_jwe)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
return;
}
// Set the AES wrap key.
jwe2.setWrappingKey(0, aes_wrapping_key, "base64url") catch {};
// Decrypt.
const jpg_original = try chilkat.BinData.init();
defer jpg_original.deinit();
success = if (jwe2.decryptBd(0, jpg_original)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
return;
}
std.debug.print("Decrypted JPG size = {d}\n", .{jpg_original.getNumBytes()});
// Save the decrypted JPG to a file.
success = if (jpg_original.writeFile("qa_output/jwe_decrypted_starfish.jpg")) true else |_| false;
std.debug.print("success = {}\n", .{success});
// The output of this program, when tested, was:
// Original JPG size = 6229
// eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.9YFz_wteV ... 7Et3hKhpxnKEXw
// size of JWE: 8473
// Decrypted JPG size = 6229
// success = True
}