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

Create JWS Using Private Key on a Smart Card

See more JSON Web Signatures (JWS) Examples

Creates and validates a JSON Web Signature (JWS) using the private key associated with a certificate on a smart card.

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 requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Load the certificate from a smart card.
    const cert = try chilkat.Cert.init();
    defer cert.deinit();

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

    // Detect the connected smartcard or USB security token and load the default certificate.
    cert.loadFromSmartcard("") catch {
        std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
        return;
    };

    // Note: Chilkat provides many different ways to load a certificate from a smartcard or USB token,
    // such as selecting a certificate if the card contains multiple certificates with private keys,
    // or working with lower-level PKCS11 or ScMinidriver API's (both of which Chilkat provides).

    // Create the JWS Protected Header
    const jws_prot_hdr = try chilkat.JsonObject.init();
    defer jws_prot_hdr.deinit();

    if (cert.isEcdsa()) {
        jws_prot_hdr.appendString("alg", "ES256") catch {};
    } else {
        jws_prot_hdr.appendString("alg", "RS256") catch {};
    }

    const jws = try chilkat.Jws.init();
    defer jws.deinit();

    // Set the protected header:
    var signature_index: i32 = 0;
    jws.setProtectedHeader(signature_index, jws_prot_hdr) catch {};

    // Provide the private key via the certificate.
    // This requires Chilkat v11.5.0 or greater.
    jws.setSigningCert(signature_index, cert) catch {};

    // Set the payload.
    const b_include_bom = false;
    const payload_str = "In our village, folks say God crumbles up the old moon into stars.";
    jws.setPayload(payload_str, "utf-8", b_include_bom) catch {};

    // Create the JWS
    // By default, the compact serialization is used.
    const jws_compact = jws.createJws(alloc) catch {
        std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("JWS: {s}\n", .{jws_compact});

    // sample output:
    // JWS: eyJhbGciOiJQUzI1NiJ9.SW4gb3VyIHZpbGxhZ2UsIGZvbGtzIHNheSBHb2QgY3J1bWJsZXMgdXAgdGhlIG9sZCBtb29uIGludG8gc3RhcnMu.TRWhwRo5dMv9-8OzrInfJTwmUGYgjLfHk8lqF072ND-FmLWEBnUTOpY8oJXp8FdWw2SalbdOeNlrtlJjwk4XK8Ql2iJ_2qMCtxsvLPhKBOqFoAF4aBvTOEDVJDxf0DaBSiydEEtfTVV2iwBcjWabu5J2XieR5y7QZQtuHsn7T3qKBvCcCejN3Y2oqAT3qMHvu1fTms1r_91wBn_K7Wjd9UkZ1n02qQcUHJznR_OF2BgN7_KWIDAF9ZS9keoju2NPpPelO4yxa2XUPnehY3G7dHKoCxUEQR4d2Xc5voqDASTVCDqQS4PVOZdvT3Ein6-SanAlCwbWBbkvT8g6-5PImQ

    // Now load the JWS, validate, and recover the original text.
    const jws2 = try chilkat.Jws.init();
    defer jws2.deinit();

    // Load the JWS.
    try jws2.loadJws(jws_compact);

    const pub_key = try chilkat.PublicKey.init();
    defer pub_key.deinit();
    cert.getPublicKey(pub_key) catch {};

    // Set the public key used for validation.
    signature_index = 0;
    jws2.setPublicKey(signature_index, pub_key) catch {};

    // Validate the 1st (and only) signature at index 0..
    const v = jws2.validate(signature_index);
    if (v < 0) {
        // Perhaps Chilkat was not unlocked or the trial expired..
        std.debug.print("Method call failed for some other reason.\n", .{});
        std.debug.print("{s}\n", .{try jws2.getLastErrorText(alloc)});
        return;
    }

    if (v == 0) {
        std.debug.print("Invalid signature.  The key was incorrect, the JWS was invalid, or both.\n", .{});
        return;
    }

    // If we get here, the signature was validated..
    std.debug.print("Signature validated.\n", .{});

    // Recover the original content:
    std.debug.print("{s}\n", .{try jws2.getPayload(alloc, "utf-8")});

    // Examine the protected header:

    const jose_header = try chilkat.JsonObject.init();
    defer jose_header.deinit();
    jws2.getProtectedH(signature_index, jose_header) catch {
        std.debug.print("{s}\n", .{try jws2.getLastErrorText(alloc)});
        return;
    };

    jose_header.setEmitCompact(false);

    std.debug.print("Protected (JOSE) header:\n", .{});
    std.debug.print("{s}\n", .{try jose_header.emit(alloc)});

    // Output:

    //     Signature validated.
    //     In our village, folks say God crumbles up the old moon into stars.
    //     Protected (JOSE) header:
    //     {
    //       "alg": "RS256"
    //     }
}