Zig Requires Chilkat v11.0.0+
Zig
RSA Hash Binary Data and Sign (and Verify)
See more RSA Examples
Demonstrates how to sign the hash of binary data. Also demonstrates how to verify the RSA signature.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_data = try chilkat.BinData.init();
defer bd_data.deinit();
bd_data.appendEncoded(original_data, "hex") catch {};
// Hash (SHA-256) and sign the hash:
const bd_signature = try chilkat.BinData.init();
defer bd_signature.deinit();
rsa.signBd(bd_data, "sha256", bd_signature) catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
// Show the RSA signature in base64
std.debug.print("{s}\n", .{try bd_signature.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..
const rsa2 = try chilkat.Rsa.init();
defer rsa2.deinit();
rsa2.usePublicKey(pub_key) catch {};
const b_verified = if (rsa2.verifyBd(bd_data, "sha256", bd_signature)) true else |_| false;
std.debug.print("signature verified: {}\n", .{b_verified});
}