void hmac_sha512(const void *key_p, const uint32_t keylen, const void *msg_p, const uint32_t msglen, uint8_t *hmac) { const uint8_t *key = key_p; const uint8_t *msg = msg_p; int i; uint8_t buf[SHA512_BLOCK_LENGTH], o_key_pad[SHA512_BLOCK_LENGTH], i_key_pad[SHA512_BLOCK_LENGTH]; SHA512_CTX ctx; memset(buf, 0, SHA512_BLOCK_LENGTH); if (keylen > SHA512_BLOCK_LENGTH) { sha512_Raw(key, keylen, buf); } else { memcpy(buf, key, keylen); } for (i = 0; i < SHA512_BLOCK_LENGTH; i++) { o_key_pad[i] = buf[i] ^ 0x5c; i_key_pad[i] = buf[i] ^ 0x36; } sha512_Init(&ctx); sha512_Update(&ctx, i_key_pad, SHA512_BLOCK_LENGTH); sha512_Update(&ctx, msg, msglen); sha512_Final(buf, &ctx); sha512_Init(&ctx); sha512_Update(&ctx, o_key_pad, SHA512_BLOCK_LENGTH); sha512_Update(&ctx, buf, SHA512_DIGEST_LENGTH); sha512_Final(hmac, &ctx); MEMSET_BZERO(buf, sizeof(buf)); MEMSET_BZERO(o_key_pad, sizeof(o_key_pad)); MEMSET_BZERO(i_key_pad, sizeof(i_key_pad)); }
void hmac_sha512_Init(HMAC_SHA512_CTX *hctx, const uint8_t *key, const uint32_t keylen) { static CONFIDENTIAL uint8_t i_key_pad[SHA512_BLOCK_LENGTH]; memzero(i_key_pad, SHA512_BLOCK_LENGTH); if (keylen > SHA512_BLOCK_LENGTH) { sha512_Raw(key, keylen, i_key_pad); } else { memcpy(i_key_pad, key, keylen); } for (int i = 0; i < SHA512_BLOCK_LENGTH; i++) { hctx->o_key_pad[i] = i_key_pad[i] ^ 0x5c; i_key_pad[i] ^= 0x36; } sha512_Init(&(hctx->ctx)); sha512_Update(&(hctx->ctx), i_key_pad, SHA512_BLOCK_LENGTH); memzero(i_key_pad, sizeof(i_key_pad)); }