Zig
Zig
Encrypt a JWE with a Recipient Public Key
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.
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. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.
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();
// Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
const header = try chilkat.JsonObject.init();
defer header.deinit();
header.updateString("alg", "RSA-OAEP-256") catch {};
header.updateString("enc", "A256GCM") catch {};
jwe.setProtectedHeader(header) 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 public key.
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
pub_key.loadFromFile("qa_data/recipient_pubkey.pem") catch {
std.debug.print("{s}\n", .{try pub_key.getLastErrorText(alloc)});
return;
};
// Set the public key used to encrypt for recipient 0.
jwe.setPublicKey(0, pub_key) catch {
std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
return;
};
const jwe_compact = jwe.encrypt(alloc, "This is the secret content.", "utf-8") catch {
std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{jwe_compact});
}