canokey-crypto is the cryptography library used by CanoKey firmware.
It provides a small, stable API surface in include/ and ships default software implementations in
src/.
Public headers:
aes.h,des.h,block-cipher.hecc.h,rsa.h,algo.hsha.h,sm3.h,sha3.h,hmac.hrand.h,crypto-util.h,memzero.h
Default implementations:
- Symmetric crypto: AES, DES/3DES, block cipher helpers
- Public-key crypto: ECC, RSA
- Hashing: SHA-1, SHA-256, SHA-512, SM3, SHA-3, SHAKE
- Helpers: HMAC, random, byte/format utilities, secure zeroization
This directory is normally built as part of canokey-core, but it can also be built standalone with CMake.
cmake -S . -B build
cmake --build buildImportant CMake options:
USE_MBEDCRYPTO=ONUse TF-PSA-Crypto / Mbed Crypto as the backend for the default implementations. This is the default.USE_MBEDCRYPTO=OFFBuild only the built-in software implementations insrc/.ENABLE_CRYPTO_TESTS=ONEnable unit tests undertest/.TEST_WITH_MBEDCRYPTO=ONWhen tests are enabled, also build cross-validation tests against Mbed Crypto.
When USE_MBEDCRYPTO=ON, the tf-psa-crypto submodule must be present.
SHA-1, SHA-256, SHA-512, and SM3 use explicit caller-provided context objects:
sha256_ctx_t ctx;
uint8_t digest[SHA256_DIGEST_LENGTH];
sha256_init(&ctx);
sha256_update(&ctx, data, data_len);
sha256_final(&ctx, digest);For one-shot hashing, use the convenience helpers:
sha1_rawsha256_rawsha512_rawsm3_rawsha3_256_rawsha3_512_rawshake128_rawshake256_raw
HMAC also uses caller-owned context:
HMAC_SHA256_CTX hctx;
uint8_t mac[SHA256_DIGEST_LENGTH];
hmac_sha256_Init(&hctx, key, key_len);
hmac_sha256_Update(&hctx, msg, msg_len);
hmac_sha256_Final(&hctx, mac);One-shot helpers are also available, such as hmac_sha1, hmac_sha256, and hmac_sha512.
SHA-3 and SHAKE already use explicit state objects via SHA3_CTX_T. The default type is sha3_ctx_t; platforms may
override it if they also override the corresponding functions.
Most default implementations in src/ are declared weak, so platform firmware can replace selected
functions with hardware-specific or ROM-backed implementations at link time.
In the CanoKey firmware tree, this is how the top-level Crypto/ directory overrides parts of the
library.
When overriding symbols, make sure the replacement matches the public header exactly. In particular:
sha.handsm3.hnow require explicit context parameters.sha3.hrequires the replacementSHA3_CTX_Tlayout to match the replacement implementation.- Overriding only part of a stateful API is unsafe; override the whole family consistently.
To build unit tests:
cmake -S . -B build -DENABLE_CRYPTO_TESTS=ON
cmake --build build
ctest --test-dir buildThe test suite uses cmocka.
- Mbed TLS / TF-PSA-Crypto: https://github.com/Mbed-TLS/mbedtls
- RHash SHA-3 code reference: https://github.com/rhash/RHash