Zig Requires Chilkat v11.0.0+
Zig
Generate RSA Key and Sign a String
See more RSA Examples
Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.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 example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const rsa = try chilkat.Rsa.init();
defer rsa.deinit();
// Generate a 2048-bit RSA key.
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
try rsa.genKey(2048, priv_key);
rsa.usePrivateKey(priv_key) catch {};
// Return the signature in hex.
rsa.setEncodingMode("hex");
const str_data = "This is the string to be signed.";
// Sign the SHA256 hash of the string.
const hex_sig = try rsa.signStringENC(alloc, str_data, "sha256");
std.debug.print("{s}\n", .{hex_sig});
// Now verify the signature:
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
priv_key.toPublicKey(pub_key) catch {};
rsa.usePublicKey(pub_key) catch {};
if (rsa.verifyStringENC(str_data, "sha256", hex_sig)) {
std.debug.print("Signature verified!\n", .{});
} else |_| {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
}
// Try it with an invalid signature:
if (rsa.verifyStringENC(str_data, "sha256", "not a valid sig")) {
std.debug.print("Signature verified!\n", .{});
} else |_| {
std.debug.print("Signature validation failed!\n", .{});
}
// Try it with invalid data:
if (rsa.verifyStringENC("Not the original data", "sha256", hex_sig)) {
std.debug.print("Signature verified!\n", .{});
} else |_| {
std.debug.print("Signature validation failed!\n", .{});
}
}