Created
October 2, 2019 09:53
-
-
Save jc-lab/833c1d60602e5bd47df9dac18fe12427 to your computer and use it in GitHub Desktop.
hmac_sha256
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void hmac_sha256(unsigned char *digest, const unsigned char *in_key, int key_length, const unsigned char *in_message, int message_length) { | |
SHA256_CTX ctx; | |
unsigned char key[64] = { 0 }; | |
unsigned char o_key_pad[64] = { 0 }; | |
unsigned char i_key_pad[64] = { 0 }; | |
unsigned char* key_pads[] = {o_key_pad, i_key_pad, NULL}; | |
unsigned char** cur_key_pad = key_pads; | |
unsigned char key_pad_xor = 0x5c; | |
if (key_length > 64) { | |
sha256_init(&ctx); | |
sha256_update(&ctx, in_key, key_length); | |
sha256_final(&ctx, key); | |
} else { | |
const unsigned char* cur_key = in_key; | |
const unsigned char* end_key = in_key + key_length; | |
unsigned char* out_key = key; | |
while (cur_key < end_key) { | |
*(out_key++) = *(cur_key++); | |
} | |
} | |
// o_key_pad ← keyxor [0x5c * blockSize] //Outer padded key | |
// i_key_pad ← keyxor [0x36 * blockSize] //Inner padded key | |
// key_pad_xor = 0x5c -> xor 0x6a -> 0x36 | |
for (; *cur_key_pad; cur_key_pad++) { | |
const unsigned char* cur_key = key; | |
const unsigned char* end_key = key + 64; | |
unsigned char* out_key = *cur_key_pad; | |
while (cur_key < end_key) { | |
*(out_key++) = *(cur_key++) ^ key_pad_xor; | |
} | |
key_pad_xor ^= 0x6A; | |
} | |
sha256_init(&ctx); | |
sha256_update(&ctx, i_key_pad, 64); | |
if(message_length) | |
sha256_update(&ctx, in_message, message_length); | |
sha256_final(&ctx, key); | |
sha256_init(&ctx); | |
sha256_update(&ctx, o_key_pad, 64); | |
sha256_update(&ctx, key, 32); | |
sha256_final(&ctx, digest); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment