Zig Requires Chilkat v11.0.0+
Zig
RSA Sign with PKCS8 Encrypted Key
See more RSA Examples
Demonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it).Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
var success: bool = false;
// 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 PEM file:
success = if (priv_key.loadAnyFormatFile("raul_privateKey.key", "a0123456789")) true else |_| false;
if (!success) {
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:
success = if (rsa.usePrivateKey(priv_key)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
}
// This example will sign a string, and receive the signature
// in a hex-encoded string. Therefore, set the encoding mode
// to "hex":
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 sha1, sha384, sha512 and others.
const hex_sig = rsa.signStringENC(alloc, str_data, "sha256") catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{hex_sig});
// Now verify with the public key.
// This example shows how to use the public key from
// a digital certificate (.cer file)
const cert = try chilkat.Cert.init();
defer cert.deinit();
success = if (cert.loadFromFile("raul_publicKey.cer")) true else |_| false;
if (!success) {
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 {};
const rsa2 = try chilkat.Rsa.init();
defer rsa2.deinit();
success = if (rsa2.usePublicKey(pub_key)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try rsa2.getLastErrorText(alloc)});
return;
}
// Verify the signature against the original data:
rsa2.setEncodingMode("hex");
success = if (rsa2.verifyStringENC(str_data, "sha256", hex_sig)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try rsa2.getLastErrorText(alloc)});
return;
}
std.debug.print("Signature verified!\n", .{});
// Verify with incorrect data:
success = if (rsa2.verifyStringENC("something else", "sha256", hex_sig)) true else |_| false;
if (!success) {
std.debug.print("Signature not verified! (which was expected in this case)\n", .{});
} else {
std.debug.print("Hmmm... that's not right...\n", .{});
}
}