Sample code for 30+ languages & platforms
Zig Requires Chilkat v10.1.2+

RSA Sign String using Private Key of Certificate Type A3 (smart card / token)

See more RSA Examples

Demonstrates RSA signing a string using the private key of a certificate type A3 (smart card, token).

Note: This is a Windows-only example.

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();

    // First get the A3 certificate that was installed on the Windows system.
    const cert_store = try chilkat.CertStore.init();
    defer cert_store.deinit();

    const thumbprint = "12c1dd8015f3f03f7b1fa619dc24e2493ca8b4b2";

    // This is specific to Windows because it is opening the Windows Current-User certificate store.
    const b_read_only = true;
    cert_store.openCurrentUserStore(b_read_only) catch {
        std.debug.print("{s}\n", .{try cert_store.getLastErrorText(alloc)});
        return;
    };

    // Find the certificate with the desired thumbprint
    // (There are many ways to locate a certificate.  This example chooses to find by thumbprint.)
    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("thumbprint", thumbprint) catch {};

    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    cert_store.findCert(json, cert) catch {
        std.debug.print("Failed to find the certificate.\n", .{});
        return;
    };

    std.debug.print("Found: {s}\n", .{try cert.getSubjectCN(alloc)});

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

    // Provide the cert's private key
    const b_use_private_key = true;
    rsa.setX509Cert(cert, b_use_private_key) catch {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    };

    // Return the RSA signature in base64 encoded form.
    rsa.setEncodingMode("base64");

    // Sign the utf-8 byte representation of the string.
    rsa.setCharset("utf-8");

    // You can also choose other hash algorithms, such as SHA-1.
    const sig_base64 = rsa.signStringENC(alloc, "text to sign", "SHA-256") catch {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Base64 signature: {s}\n", .{sig_base64});
}