
Zig Hardware Security Module library for PIV, CAC, and YubiKey tokens via PC/SC. Supports certificates, PIN management, signing, and decryption.
A Hardware Security Module (HSM) library for Zig providing PC/SC access to PIV, CAC, and YubiKey tokens.
| Aspect | Info |
|---|---|
| API Stability | Development |
| Zig Version | 0.16.0 |
| Platforms | Linux, macOS, Windows |
| License | MIT |
PIV Support (NIST SP 800-73-4)
CAC Support (Common Access Card)
YubiKey Support
Security
anyerror)Parallel Operations (via thread_pool)
-Denable_tp=true); disable with -Denable_tp=falselibpcsclite-dev (Debian/Ubuntu) or pcsc-lite-devel (Fedora)# 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
# 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
| Option | Default | Description | Security Impact |
|---|---|---|---|
integration_sim | false | Run simulator integration tests | None |
hsm_hil | false | Run hardware-in-loop tests (requires real token) | None |
link_pcsc | false | Link PC/SC library for examples | None |
include_simulator | Debug: trueRelease: false | Include PIV simulator with test keys | CWE-321: Test keys in production |
allow_pcsc_env_override | false | SECURITY RISK: Allow HSM_PCSC_LIB_PATH env var | CWE-427: Untrusted library loading |
fips | false | Route 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 |
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:
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});
}
| Type | Description |
|---|---|
TokenKind | Token type: .piv, .cac, .yubikey, .unknown |
TokenInfo | Discovered token metadata |
Token | Open token handle for operations |
Slot | Key slot: .authentication (9A), .signature (9C), .key_management (9D), .card_auth (9E) |
Algorithm | Crypto algorithm: .ecdsa_p256, .ecdsa_p384, .rsa2048_pkcs1v15, etc. |
Capabilities | Token capability flags |
PcscScope | PC/SC context scope: .user (default), .system |
| Function | Description |
|---|---|
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 |
All operations return errors from HsmError:
PcscUnavailable, ReaderGone, CardRemoved, TimeoutPinIncorrect, PinLocked, PinLengthInvalidNotSupported, SlotNotFound, AlgorithmNotSupportedInvalidTlv, CertificateNotFound, InvalidDigestLengthSecurityConditionNotSatisfied, AuthenticationFailedThe 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.
| Function | Description | Threshold |
|---|---|---|
parallelSign(allocator, inputs, results) | Batch signing across slots | 2+ items |
parallelDecrypt(allocator, inputs, results) | Batch decryption across keys | 2+ items |
parallelTokenDiscover(readers, results) | Token discovery across readers | 2+ readers |
parallelCertRetrieve(allocator, requests, results) | Certificate retrieval across slots | 2+ requests |