/* * LITLS -- HMAC-SHA256 and HMAC-SHA384 (RFC 2104) */ #include "litls.h" #include void litls_hmac_sha256(const uint8_t *key, size_t key_len, const uint8_t *msg, size_t msg_len, uint8_t out[32]) { uint8_t k_pad[LITLS_SHA256_BLOCK_SIZE]; uint8_t inner_hash[32]; litls_sha256_ctx ctx; /* If key is longer than block size, hash it */ uint8_t key_hash[32]; if (key_len > LITLS_SHA256_BLOCK_SIZE) { litls_sha256(key, key_len, key_hash); key = key_hash; key_len = 32; } /* ipad = key XOR 0x36 */ memset(k_pad, 0x36, LITLS_SHA256_BLOCK_SIZE); for (size_t i = 0; i < key_len; i++) k_pad[i] ^= key[i]; litls_sha256_init(&ctx); litls_sha256_update(&ctx, k_pad, LITLS_SHA256_BLOCK_SIZE); litls_sha256_update(&ctx, msg, msg_len); litls_sha256_final(&ctx, inner_hash); /* opad = key XOR 0x5c */ memset(k_pad, 0x5c, LITLS_SHA256_BLOCK_SIZE); for (size_t i = 0; i < key_len; i++) k_pad[i] ^= key[i]; litls_sha256_init(&ctx); litls_sha256_update(&ctx, k_pad, LITLS_SHA256_BLOCK_SIZE); litls_sha256_update(&ctx, inner_hash, 32); litls_sha256_final(&ctx, out); } void litls_hmac_sha384(const uint8_t *key, size_t key_len, const uint8_t *msg, size_t msg_len, uint8_t out[48]) { uint8_t k_pad[LITLS_SHA384_BLOCK_SIZE]; uint8_t inner_hash[48]; litls_sha384_ctx ctx; uint8_t key_hash[48]; if (key_len > LITLS_SHA384_BLOCK_SIZE) { litls_sha384(key, key_len, key_hash); key = key_hash; key_len = 48; } memset(k_pad, 0x36, LITLS_SHA384_BLOCK_SIZE); for (size_t i = 0; i < key_len; i++) k_pad[i] ^= key[i]; litls_sha384_init(&ctx); litls_sha384_update(&ctx, k_pad, LITLS_SHA384_BLOCK_SIZE); litls_sha384_update(&ctx, msg, msg_len); litls_sha384_final(&ctx, inner_hash); memset(k_pad, 0x5c, LITLS_SHA384_BLOCK_SIZE); for (size_t i = 0; i < key_len; i++) k_pad[i] ^= key[i]; litls_sha384_init(&ctx); litls_sha384_update(&ctx, k_pad, LITLS_SHA384_BLOCK_SIZE); litls_sha384_update(&ctx, inner_hash, 48); litls_sha384_final(&ctx, out); }