| 1 | /* |
| 2 | * sha256.h - SHA-256 (FIPS 180-4) and HMAC-SHA256 (RFC 2104) in pure C99. |
| 3 | * |
| 4 | * The plugin signs outbound webhook bodies with HMAC-SHA256, so it needs a |
| 5 | * digest that is correct rather than convenient. This implementation is the |
| 6 | * textbook one: no tables generated at run time, no allocation, no global |
| 7 | * state, and the two FIPS/RFC test vectors in tests/run.sh are the contract. |
| 8 | * |
| 9 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 10 | */ |
| 11 | #ifndef SX_WH_SHA256_H |
| 12 | #define SX_WH_SHA256_H |
| 13 | |
| 14 | #include <stddef.h> |
| 15 | #include <stdint.h> |
| 16 | |
| 17 | #define SX_SHA256_DIGEST_LEN 32 |
| 18 | #define SX_SHA256_HEX_LEN 64 |
| 19 | |
| 20 | typedef struct { |
| 21 | uint32_t h[8]; |
| 22 | uint64_t bits; /* total message length in bits */ |
| 23 | unsigned char buf[64]; |
| 24 | size_t used; /* bytes currently in buf */ |
| 25 | } sx_sha256; |
| 26 | |
| 27 | void sx_sha256_init(sx_sha256 *c); |
| 28 | void sx_sha256_update(sx_sha256 *c, const void *data, size_t len); |
| 29 | void sx_sha256_final(sx_sha256 *c, unsigned char out[SX_SHA256_DIGEST_LEN]); |
| 30 | |
| 31 | /* Convenience: lowercase hex + NUL into `hex` (65 bytes). */ |
| 32 | void sx_sha256_hex(const void *data, size_t len, char hex[SX_SHA256_HEX_LEN + 1]); |
| 33 | |
| 34 | /* HMAC-SHA256 over `len` bytes of `msg` with `klen` bytes of key. |
| 35 | * Writes the raw 32-byte tag into out. */ |
| 36 | void sx_hmac_sha256(const void *key, size_t klen, |
| 37 | const void *msg, size_t len, |
| 38 | unsigned char out[SX_SHA256_DIGEST_LEN]); |
| 39 | |
| 40 | /* HMAC-SHA256 as lowercase hex + NUL (65 bytes). */ |
| 41 | void sx_hmac_sha256_hex(const void *key, size_t klen, |
| 42 | const void *msg, size_t len, |
| 43 | char hex[SX_SHA256_HEX_LEN + 1]); |
| 44 | |
| 45 | /* Constant-time compare of two equal-length buffers. 1 when equal. |
| 46 | * Used for signature checks so a mismatch costs the same as a match. */ |
| 47 | int sx_ct_eq(const unsigned char *a, const unsigned char *b, size_t n); |
| 48 | |
| 49 | #endif /* SX_WH_SHA256_H */ |