Skip to content
KitploitKITPLOIT
ToolsExploitsBlog
Log in
Submit
ToolsExploitsBlog
Submit

Hacking, PenTest, and Cybersecurity Tools for Your Security Arsenal!

Kitploit is a directory of hacking, cybersecurity, and pentesting tools. Discover the latest project updates to find vulnerabilities, analyze systems, automate testing, and strengthen your security.

··Feeds·Contact·Privacy·© 2026 Kitploit

Tool Directory

Categories

View all categories
Loading categories
hsm — Zig Hardware Security Module library for PIV, CAC, and YubiKey tokens via PC/SC. Supports certificates, PIN management, signing, and decryption. | Kitploit
Tools/GitLabGitLab/devnw/zig/hsm
Encryption/Decryption ToolsCryptographyHardware SecurityAuthentication
GitLabdevnw/zig/hsm

hsm

Zig Hardware Security Module library for PIV, CAC, and YubiKey tokens via PC/SC. Supports certificates, PIN management, signing, and decryption.

View Repository
1620 days agoNot yet reviewed

Most Popular

View all →

Discover the most used tools by our community.

Explore all tools

Browse our collection of tools

View all tools →
Share

zhsm

A Hardware Security Module (HSM) library for Zig providing PC/SC access to PIV, CAC, and YubiKey tokens.

Status

AspectInfo
API StabilityDevelopment
Zig Version0.16.0
PlatformsLinux, macOS, Windows
LicenseMIT

Features

  • PIV Support (NIST SP 800-73-4)

    • Certificate retrieval (slots 9A, 9C, 9D, 9E)
    • PIN verification, change, and unblock
    • ECDSA P-256/P-384 signing
    • RSA 2048/3072/4096 signing
    • RSA decryption
  • CAC Support (Common Access Card)

    • Modern PIV-compatible CACs (full operations)
    • Legacy CAC PKI applet detection (applet selection only)
  • YubiKey Support

    • PIV applet operations
    • ATR-based detection
    • Optional management commands
  • Security

    • No secrets in logs (redacted debug mode)
    • Sensitive buffer zeroization
    • Strict TLV parsing with depth/length limits
    • Tight error types (no anyerror)
    • Session-bound PIN verification (ATR-based card swap detection)
  • Parallel Operations (via thread_pool)

    • Batch signing across multiple slots
    • Batch decryption across multiple keys
    • Parallel token discovery across readers
    • Parallel certificate retrieval across slots
    • Automatic sequential fallback below threshold (< 2 items)
    • Enabled by default (-Denable_tp=true); disable with -Denable_tp=false

Requirements

  • Zig 0.16.0 or compatible
  • PC/SC Library:
    • Linux: libpcsclite-dev (Debian/Ubuntu) or pcsc-lite-devel (Fedora)
    • macOS: Built-in PCSC.framework
    • Windows: Built-in Winscard.dll

Installing PC/SC on Linux

# Debian/Ubuntu
sudo apt-get install libpcsclite-dev pcscd

# Fedora/RHEL
sudo dnf install pcsc-lite-devel pcsc-lite

# Start the PC/SC daemon
sudo systemctl start pcscd
sudo systemctl enable pcscd

Building

# Build and run unit tests
make

# Or using zig directly
zig build test

# Run simulator integration tests
zig build test -Dintegration_sim=true

# Build examples (requires PC/SC library installed)
zig build examples -Dlink_pcsc=true

Build Options

OptionDefaultDescriptionSecurity Impact
integration_simfalseRun simulator integration testsNone
hsm_hilfalseRun hardware-in-loop tests (requires real token)None
link_pcscfalseLink PC/SC library for examplesNone
include_simulatorDebug: true
Release: false
Include PIV simulator with test keysCWE-321: Test keys in production
allow_pcsc_env_overridefalseSECURITY RISK: Allow HSM_PCSC_LIB_PATH env varCWE-427: Untrusted library loading
fipsfalseRoute security crypto through the linked FIPS-140-3 provider (zero overhead when off)None when off
openssl_path(unset)OpenSSL install prefix for non-standard installs (e.g. /usr/local/ssl)None

FIPS-140-3 / PQC mode

With -Dfips=true, every security-relevant cryptographic primitive routes through a linked, validated OpenSSL 3.x FIPS provider via the crypto_backend seam, and the simulator gains post-quantum PIV token operations (ML-DSA-65 signing, ML-KEM-768 encap/decap) that are available only in FIPS mode. The flag is off by default with zero overhead; the fips dependency is resolved only under -Dfips=true.

# Default build — std.crypto backend, no OpenSSL link
zig build test

# FIPS build — OpenSSL FIPS provider (run `make deps` from fips first)
OPENSSL_CONF=/usr/local/ssl/ssl/openssl.cnf \
  zig build test -Dfips=true -Dopenssl_path=/usr/local/ssl

# Both modes in one shot
make test-dual

See docs/FIPS.md for the seam design, the fips-exempt policy, and the PQC token operations.

Security Note: The allow_pcsc_env_override option is disabled by default to prevent malicious library injection attacks (CWE-427). Only enable this for development/testing:

# Production build (secure, env var ignored)
zig build

# Development build (allows HSM_PCSC_LIB_PATH)
zig build -Dallow_pcsc_env_override=true

When enabled, libraries are validated before loading:

  • Must be absolute paths
  • Cannot be world-writable
  • Warns on group-writable files

Quick Start

const std = @import("std");
const hsm = @import("hsm");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // List available tokens
    const tokens = try hsm.listTokens(allocator, false);
    defer {
        for (tokens) |*t| t.deinit();
        allocator.free(tokens);
    }

    if (tokens.len == 0) {
        std.debug.print("No tokens found\n", .{});
        return;
    }

    // Open the first token
    var token = try hsm.openToken(allocator, tokens[0].id, .{});
    defer token.close();

    // Verify PIN
    try token.verifyPin("123456");

    // Read certificate
    const cert = try token.getCertificate(.authentication);
    defer allocator.free(cert);
    std.debug.print("Certificate: {} bytes\n", .{cert.len});

    // Sign a digest
    var digest: [32]u8 = undefined;
    std.crypto.hash.sha2.Sha256.hash("Hello, PIV!", &digest, .{});

    const signature = try token.sign(.authentication, .ecdsa_p256, &digest);
    defer allocator.free(signature);
    std.debug.print("Signature: {} bytes\n", .{signature.len});
}

API Overview

Types

TypeDescription
TokenKindToken type: .piv, .cac, .yubikey, .unknown
TokenInfoDiscovered token metadata
TokenOpen token handle for operations
SlotKey slot: .authentication (9A), .signature (9C), .key_management (9D), .card_auth (9E)
AlgorithmCrypto algorithm: .ecdsa_p256, .ecdsa_p384, .rsa2048_pkcs1v15, etc.
CapabilitiesToken capability flags
PcscScopePC/SC context scope: .user (default), .system

Functions

FunctionDescription
listTokens(allocator, use_sim)List available tokens
openToken(allocator, id, opts)Open a token by ID
token.reconnect()Reconnect to token and reset auth state
token.verifyPin(pin)Verify PIN
token.changePin(old, new)Change PIN
token.unblockPin(puk, new_pin)Unblock PIN with PUK
token.getCertificate(slot)Get DER-encoded certificate
token.sign(slot, alg, digest)Sign a digest
token.decrypt(slot, alg, ciphertext)Decrypt data
token.capabilities()Get token capabilities
token.close()Close token connection

Errors

All operations return errors from HsmError:

  • PC/SC: PcscUnavailable, ReaderGone, CardRemoved, Timeout
  • PIN: PinIncorrect, PinLocked, PinLengthInvalid
  • Capability: NotSupported, SlotNotFound, AlgorithmNotSupported
  • Data: InvalidTlv, CertificateNotFound, InvalidDigestLength
  • Security: SecurityConditionNotSatisfied, AuthenticationFailed

Parallel Operations Module

The parallel module provides batch HSM operations using the thread_pool library. It is built as a separate Zig module and available when -Denable_tp=true (the default). Set -Denable_tp=false to compile out the seam entirely; the public functions still exist and fall back to a sequential implementation.

FunctionDescriptionThreshold
parallelSign(allocator, inputs, results)Batch signing across slots2+ items
parallelDecrypt(allocator, inputs, results)Batch decryption across keys2+ items
parallelTokenDiscover(readers, results)Token discovery across readers2+ readers
parallelCertRetrieve(allocator, requests, results)Certificate retrieval across slots2+ requests
Download Tool