Zig Requires Chilkat v11.0.0+
Zig
RSA Sign Binary Data and Verify (Recover the Original Data)
See more RSA Examples
Demonstrates how to RSA sign binary data and then verify/recover the original data.Note: This example uses methods introduced in Chilkat v9.5.0.77.
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 requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load an RSA private key for signing.
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
priv_key.loadEncryptedPemFile("qa_data/pem/rsa_passwd.pem", "passwd") catch {
std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
return;
};
const rsa = try chilkat.Rsa.init();
defer rsa.deinit();
rsa.usePrivateKey(priv_key) catch {};
// We have some binary data (in hex) to sign
const original_data = "0102030405060708090A";
const bd = try chilkat.BinData.init();
defer bd.deinit();
bd.appendEncoded(original_data, "hex") catch {};
// If successful, the contents of bd are replaced with the RSA signature.
rsa.signRawBd(bd) catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
// Show the RSA signature in base64
std.debug.print("{s}\n", .{try bd.getEncoded(alloc, "base64")});
// ------------------------------------------
// Get the public key from the private key
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
priv_key.toPublicKey(pub_key) catch {};
// Verify the signature and extract the original data.
const rsa2 = try chilkat.Rsa.init();
defer rsa2.deinit();
rsa2.usePublicKey(pub_key) catch {};
const b_verified = if (rsa2.verifyRawBd(bd)) true else |_| false;
std.debug.print("signature verified: {}\n", .{b_verified});
// Show the original data:
std.debug.print("original data: {s}\n", .{try bd.getEncoded(alloc, "hex")});
}