Zig Requires Chilkat v11.0.0+
Zig
RSA Signature/Verify with .key and .cer
See more RSA Examples
Demonstrates how to use a .key file (private key) and digital certificate (.cer, public key) to create and verify an 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 assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
// Load the private key from an RSA .key file:
priv_key.loadPemFile("privateKey.key") catch {
std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
return;
};
const rsa = try chilkat.Rsa.init();
defer rsa.deinit();
// Import the private key into the RSA component:
rsa.usePrivateKey(priv_key) catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
// Create the signature as a hex string:
rsa.setEncodingMode("hex");
const str_data = "This is the string to be signed.";
// Sign the string using the sha256 hash algorithm.
// Other valid choices are "md2", "sha1", "sha384",
// "sha512", and "md5".
const hex_sig = try rsa.signStringENC(alloc, str_data, "sha256");
std.debug.print("{s}\n", .{hex_sig});
// Load a digital certificate from a .cer file:
const cert = try chilkat.Cert.init();
defer cert.deinit();
cert.loadFromFile("myCert.cer") catch {
std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
return;
};
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
cert.getPublicKey(pub_key) catch {};
// Now verify using a new instance of the RSA object:
const rsa2 = try chilkat.Rsa.init();
defer rsa2.deinit();
// Import the public key into the RSA object:
rsa2.usePublicKey(pub_key) catch {
std.debug.print("{s}\n", .{try rsa2.getLastErrorText(alloc)});
return;
};
// The signature is a hex string, so make sure the EncodingMode is correct:
rsa2.setEncodingMode("hex");
// Verify the signature:
rsa2.verifyStringENC(str_data, "sha256", hex_sig) catch {
std.debug.print("{s}\n", .{try rsa2.getLastErrorText(alloc)});
return;
};
std.debug.print("Success.\n", .{});
}