openaliro
Aliro reader: UWB/CCC core and ESP32-S3/C5/C6 port
Loading...
Searching...
No Matches
aliro_hash.h
1// Streaming SHA-256 (FIPS 180-4) implementation used by the Aliro crypto layer.
2// Declares struct aliro_sha256, the incremental hash context used across init/update/finish
3// calls.
4/*
5 * Copyright (c) 2026 asxeem
6 * SPDX-License-Identifier: ISC
7 *
8 * aliro_hash — portable SHA-256 and its KDF constructions (HMAC-SHA256,
9 * HKDF-SHA256, ANSI-X9.63 KDF). Pure C11, no platform dependency, so the exact
10 * same object is compiled on the ESP32 target and in the host known-answer
11 * tests: a host KAT here is a direct proof of the on-target key schedule.
12 *
13 * These are the building blocks of the Aliro credential-auth key derivation
14 * (see aliro_crypto.h). AES-GCM and P-256 (ECDH/ECDSA) are NOT here; those use
15 * the platform crypto backend (mbedTLS-PSA on target).
16 */
17#pragma once
18
19#include <stddef.h>
20#include <stdint.h>
21
22#ifdef __cplusplus
23extern "C" {
24#endif
25
26#define ALIRO_SHA256_BLOCK 64u
27#define ALIRO_SHA256_LEN 32u
28
29/* Streaming SHA-256 (FIPS 180-4). */
30struct aliro_sha256 {
31 uint32_t h[8];
32 uint64_t total; /* message length in bytes */
33 uint8_t buf[ALIRO_SHA256_BLOCK];
34 size_t buflen;
35};
36
37void aliro_sha256_init(struct aliro_sha256 *s);
38void aliro_sha256_update(struct aliro_sha256 *s, const void *data, size_t len);
39void aliro_sha256_final(struct aliro_sha256 *s, uint8_t out[ALIRO_SHA256_LEN]);
40
41/* One-shot SHA-256. */
42void aliro_sha256(const void *data, size_t len, uint8_t out[ALIRO_SHA256_LEN]);
43
44/* HMAC-SHA256 (RFC 2104). out is 32 bytes. */
45void aliro_hmac_sha256(const uint8_t *key, size_t key_len, const void *msg, size_t msg_len,
46 uint8_t out[ALIRO_SHA256_LEN]);
47
48/*
49 * HKDF-SHA256 (RFC 5869).
50 * extract: PRK = HMAC(salt, ikm); salt==NULL uses a 32-byte zero salt.
51 * expand: OKM = T(1)|T(2)|... truncated to out_len (<= 255*32).
52 * Returns 0 on success, -1 on a bad length.
53 */
54void aliro_hkdf_extract(const uint8_t *salt, size_t salt_len, const uint8_t *ikm, size_t ikm_len,
55 uint8_t prk[ALIRO_SHA256_LEN]);
56int aliro_hkdf_expand(const uint8_t prk[ALIRO_SHA256_LEN], const uint8_t *info, size_t info_len,
57 uint8_t *out, size_t out_len);
58int aliro_hkdf(const uint8_t *salt, size_t salt_len, const uint8_t *ikm, size_t ikm_len,
59 const uint8_t *info, size_t info_len, uint8_t *out, size_t out_len);
60
61/*
62 * ANSI-X9.63 KDF (SEC1 v2 KDF2), SHA-256 variant:
63 * OKM = Hash(Z | counter_be32=1 | info) | Hash(Z | counter=2 | info) | ...
64 * truncated to out_len. Returns 0 on success, -1 on a bad length.
65 */
66int aliro_x963_kdf(const uint8_t *z, size_t z_len, const uint8_t *info, size_t info_len,
67 uint8_t *out, size_t out_len);
68
69#ifdef __cplusplus
70}
71#endif