Smart Card Communication
smartcard
Experimental Zig library for smart card communication. This is a personal project for playing around with card readers and is provided as-is with no guarantees.
- pcsc -- direct card access via the platform PC/SC provider (no dependencies)
- pkcs11 -- bindings for PKCS#11 v3.1 middleware
- iso7816 -- ISO 7816-4 APDU command building and response parsing
- tlv -- BER-TLV (ISO 7816-4 Annex D) encoding and decoding
- belpic -- Belgian eID card support (identity, address, photo, certificates, PIN, signing)
Platform
| OS | PC/SC provider | Status |
|---|---|---|
| macOS | PCSC.framework (built-in) | Tested |
| Linux | pcsclite (libpcsclite-dev) |
Tested |
| Windows | winscard (built-in) | Tested |
Usage
PC/SC (direct card access)
constpcsc=@import("smartcard").pcsc;constctx=trypcsc.Context.establish(pcsc.SCARD_SCOPE_SYSTEM);deferctx.release();constreaders=tryctx.listReaders(allocator);constcard=tryctx.connect(readers[0],pcsc.SCARD_SHARE_SHARED,pcsc.SCARD_PROTOCOL_ANY);defercard.disconnect(pcsc.SCARD_LEAVE_CARD);// Send an APDUvarrecv_buf:[256]u8=undefined;constresponse=trycard.transmit(&apdu,&recv_buf);PKCS#11 (middleware)
constpkcs11=@import("smartcard").pkcs11;varlib=trypkcs11.Library.load("/path/to/pkcs11-middleware.so");deferlib.close();trylib.initialize(null);deferlib.finalize()catch{};constinfo=trylib.getInfo();Examples
Read a Belgian eID card (requires a connected card reader). Tested with an ACS ACR122U (AC6020) USB reader.
zig build belpic
Testing
zig build test
PKCS#11 tests run against SoftHSM2 if available. If softhsm2-util is not on PATH, those tests are skipped. PC/SC tests require a running smartcard daemon and skip gracefully if unavailable.
On Linux, install the pcsclite development headers:
sudo apt install libpcsclite-dev # Debian/Ubuntu
References
- ISO/IEC 7816-4 -- Smart card commands, APDU structure, BER-TLV encoding
- PC/SC Workgroup Specifications -- PC/SC API for card reader access
- PKCS#11 v3.1 (OASIS) -- Cryptographic Token Interface Standard
- PKCS#11 v3.1 Header Files -- C header files
- SoftHSM2 -- Software HSM for testing PKCS#11
- Apple CryptoTokenKit / PCSC.framework -- macOS smart card framework
- pcsclite -- Linux PC/SC middleware
- Belgian eID middleware -- Belgian Electronic Identity Card specifications and middleware