Zig
Zig
RSA Sign utf-8 Bytes of String to get Base64 RSA Signature
See more Apple Keychain Examples
Demonstrates how RSA sign the utf-8 byte representation of a string to get the signature in base64 format.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// 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.
cert.loadFromSmartcard("cn=chilkat-rsa-2048") catch {
std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
return;
};
std.debug.print("Signing with cert: {s}\n", .{try cert.getSubjectCN(alloc)});
// Create a string to be hashed and signed.
const sb = try chilkat.StringBuilder.init();
defer sb.deinit();
const crlf_line_ending = true;
var i: i32 = 0;
i = 0;
while (i <= 10) : (i += 1) {
sb.appendLine("This is a test.", crlf_line_ending) catch {};
}
const rsa = try chilkat.Rsa.init();
defer rsa.deinit();
// Use the certificate's private key for signing.
rsa.setX509Cert(cert, true) catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
// Sign the SHA-256 hash of the utf-8 byte representation of the contents of sb
// Return the signature in base64 format.
rsa.setEncodingMode("base64");
rsa.setCharset("utf-8");
const string_to_sign = try sb.getAsString(alloc);
const sig_base64 = rsa.signStringENC(alloc, string_to_sign, "sha256") catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
std.debug.print("RSA signature as base64: {s}\n", .{sig_base64});
}