Zig
Zig
Encrypt a JWE with a Password (PBES2)
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.SetPassword, which sets the PBES2 password for a recipient. The example uses PBES2-HS256+A128KW key management with AES-128-GCM content encryption.
Background. PBES2 derives a key-wrapping key from a password using a salt and iteration count, allowing password-based JWE encryption. The password should come from a secure source.
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: PBES2 password-based key management with AES-128-GCM content encryption.
const header = try chilkat.JsonObject.init();
defer header.deinit();
header.updateString("alg", "PBES2-HS256+A128KW") catch {};
header.updateString("enc", "A128GCM") catch {};
jwe.setProtectedHeader(header) catch {
std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
return;
};
// Set the PBES2 password for recipient 0. The password should come from a secure source rather than
// being hard-coded.
const password = "myPassword";
jwe.setPassword(0, password) 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});
}