| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <string.h> |
| 4 |
|
| 5 |
#include "hmac.h" |
| 6 |
#include "memory-util.h" |
| 7 |
#include "sha256.h" |
| 8 |
|
| 9 |
#define HMAC_BLOCK_SIZE 64 |
| 10 |
#define INNER_PADDING_BYTE 0x36 |
| 11 |
#define OUTER_PADDING_BYTE 0x5c |
| 12 |
|
| 13 |
void hmac_sha256(const void *key, |
| 14 |
size_t key_size, |
| 15 |
const void *input, |
| 16 |
size_t input_size, |
| 17 |
uint8_t res[static SHA256_DIGEST_SIZE]) { |
| 18 |
|
| 19 |
uint8_t inner_padding[HMAC_BLOCK_SIZE] = { }; |
| 20 |
CLEANUP_ERASE(inner_padding); /* carries key ^ 0x36, trivially reversible to the original key */ |
| 21 |
uint8_t outer_padding[HMAC_BLOCK_SIZE] = { }; |
| 22 |
CLEANUP_ERASE(outer_padding); /* carries key ^ 0x5c, trivially reversible to the original key */ |
| 23 |
uint8_t replacement_key[SHA256_DIGEST_SIZE]; |
| 24 |
CLEANUP_ERASE(replacement_key); /* SHA-256 of the key when key_size > block size */ |
| 25 |
struct sha256_ctx hash; |
| 26 |
CLEANUP_ERASE(hash); /* intermediate state derived from key material */ |
| 27 |
|
| 28 |
assert(key); |
| 29 |
assert(key_size > 0); |
| 30 |
assert(res); |
| 31 |
|
| 32 |
/* Implement algorithm as described by FIPS 198. */ |
| 33 |
|
| 34 |
/* The key needs to be block size length or less, hash it if it's longer. */ |
| 35 |
if (key_size > HMAC_BLOCK_SIZE) { |
| 36 |
sha256_direct(key, key_size, replacement_key); |
| 37 |
key = replacement_key; |
| 38 |
key_size = SHA256_DIGEST_SIZE; |
| 39 |
} |
| 40 |
|
| 41 |
/* First, copy the key into the padding arrays. If it's shorter than |
| 42 |
* the block size, the arrays are already initialized to 0. */ |
| 43 |
memcpy(inner_padding, key, key_size); |
| 44 |
memcpy(outer_padding, key, key_size); |
| 45 |
|
| 46 |
/* Then, XOR the provided key and any padding leftovers with the fixed |
| 47 |
* padding bytes as defined in FIPS 198. */ |
| 48 |
for (size_t i = 0; i < HMAC_BLOCK_SIZE; i++) { |
| 49 |
inner_padding[i] ^= INNER_PADDING_BYTE; |
| 50 |
outer_padding[i] ^= OUTER_PADDING_BYTE; |
| 51 |
} |
| 52 |
|
| 53 |
/* First pass: hash the inner padding array and the input. */ |
| 54 |
sha256_init_ctx(&hash); |
| 55 |
sha256_process_bytes(inner_padding, HMAC_BLOCK_SIZE, &hash); |
| 56 |
sha256_process_bytes(input, input_size, &hash); |
| 57 |
sha256_finish_ctx(&hash, res); |
| 58 |
|
| 59 |
/* Second pass: hash the outer padding array and the result of the first pass. */ |
| 60 |
sha256_init_ctx(&hash); |
| 61 |
sha256_process_bytes(outer_padding, HMAC_BLOCK_SIZE, &hash); |
| 62 |
sha256_process_bytes(res, SHA256_DIGEST_SIZE, &hash); |
| 63 |
sha256_finish_ctx(&hash, res); |
| 64 |
} |