Skip to content

Instantly share code, notes, and snippets.

@jc-lab
Created October 2, 2019 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jc-lab/833c1d60602e5bd47df9dac18fe12427 to your computer and use it in GitHub Desktop.
Save jc-lab/833c1d60602e5bd47df9dac18fe12427 to your computer and use it in GitHub Desktop.
hmac_sha256
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