Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

Verify the RSA Signature of a SHA256 Hash

See more RSA Examples

Demonstrates how to verify an RSA signature of a SHA256 hash.

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

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Let's say you have a file containing the 32-bytes of a SHA256 hash,
    // and a file that is an RSA signature of those 32 bytes.
    // Here's how you verify using the RSA public key found in a PEM.

    const pub_key = try chilkat.PublicKey.init();
    defer pub_key.deinit();
    pub_key.loadFromFile("rsaPubKey.pem") catch {
        std.debug.print("{s}\n", .{try pub_key.getLastErrorText(alloc)});
        return;
    };

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

    // Get the public key.
    rsa.usePublicKey(pub_key) catch {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    };

    // Get the 32-byte SHA256 hash.
    const bd_hash = try chilkat.BinData.init();
    defer bd_hash.deinit();
    bd_hash.loadFile("myHash.sha256") catch {
        std.debug.print("Failed to load SHA256 hash.\n", .{});
        return;
    };

    // Get the RSA signature to be validated.
    const bd_sig = try chilkat.BinData.init();
    defer bd_sig.deinit();
    bd_sig.loadFile("mySig.sig") catch {
        std.debug.print("Failed to load RSA signature.\n", .{});
        return;
    };

    // Verify the signature against the SHA256 hash.
    const enc = "base64";
    rsa.setEncodingMode(enc);
    rsa.verifyHashENC(try bd_hash.getEncoded(alloc, enc), "sha256", try bd_sig.getEncoded(alloc, enc)) catch {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Signature validated.\n", .{});
}