Sample code for 30+ languages & platforms
Zig

RSA Sign an Encoded Hash

See more RSA Examples

Demonstrates signing a hash (e.g., SHA256) provided as an encoded string (e.g., base64 or hex).

Chilkat Zig Downloads

Zig
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;

    // Assuming the smartcard/USB token is installed with the correct drivers from the manufacturer,
    // this code can work on multiple platforms including Windows, MacOS, Linux, and iOS.

    // Chilkat automatically detects and determines the way in which the HSM is used,
    // which can be by PKCS11, Apple Keychain, Microsoft CNG / Crypto API, or ScMinidriver.

    const cert = try chilkat.Cert.init();
    defer cert.deinit();

    // Set the token/smartcard PIN prior to loading.
    cert.setSmartCardPin("123456");

    // Specify the certificate by its common name.
    success = if (cert.loadFromSmartcard("cn=chilkat-rsa-2048")) true else |_| false;
    if (!success) {
        std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
        return;
    }

    std.debug.print("Signing with the private key for this cert: {s}\n", .{try cert.getSubjectCN(alloc)});

    // Create data to be hashed and signed.
    const bd = try chilkat.BinData.init();
    defer bd.deinit();
    var i: i32 = 0;
    i = 0;
    while (i <= 100) : (i += 1) {
        bd.appendEncoded("000102030405060708090A0B0C0D0E0F", "hex") catch {};
    }

    const rsa = try chilkat.Rsa.init();
    defer rsa.deinit();

    // Use the certificate's private key for signing.
    success = if (rsa.setX509Cert(cert, true)) true else |_| false;
    if (!success) {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    }

    // We'll first compute the hash and then pass the encoded hash to be signed.
    const sha256_base64 = try bd.getHash(alloc, "sha256", "base64");
    std.debug.print("sha256 hash in base64 format: {s}\n", .{sha256_base64});

    // Pass in the base64 hash and return a base64 signature.
    rsa.setEncodingMode("base64");
    const rsa_sig_base64 = try rsa.signHashENC(alloc, sha256_base64, "sha256");
    if (!success) {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    }

    std.debug.print("RSA signature as base64: {s}\n", .{rsa_sig_base64});
}