hmac_sha2_256.c (1543B)
1 #include <assert.h> 2 3 #include <skalibs/sha256.h> 4 5 #include "hmac_b2s_256.h" 6 7 /* function doing the HMAC-SHA-256 calculation */ 8 void hmac_sha256(const uint8_t* key, const uint32_t keysize, const uint8_t* msg, const uint32_t msgsize, uint8_t* output) 9 { 10 static const size_t block_size = 64, digest_size = 32; 11 SHA256Schedule outer, inner; 12 uint8_t tmp; 13 14 if (keysize > block_size) // if len(key) > blocksize(sha256) => key = sha256(key) 15 { 16 uint8_t new_key[digest_size]; 17 sha256_init(&outer); 18 sha256_update(&outer, key, keysize); 19 sha256_final(&outer, new_key); 20 return hmac_sha256(new_key, digest_size, msg, msgsize, output); 21 } 22 sha256_init(&outer); 23 sha256_init(&inner); 24 25 uint32_t i; 26 for (i = 0; i < keysize; ++i) 27 { 28 tmp = key[i] ^ 0x5C; 29 sha256_update(&outer, &tmp, 1); 30 tmp = key[i] ^ 0x36; 31 sha256_update(&inner, &tmp, 1); 32 } 33 for (; i < block_size; ++i) 34 { 35 tmp = 0x5C; 36 sha256_update(&outer, &tmp, 1); 37 tmp = 0x36; 38 sha256_update(&inner, &tmp, 1); 39 } 40 41 sha256_update(&inner, msg, msgsize); 42 sha256_final(&inner, output); 43 44 sha256_update(&outer, output, digest_size); 45 sha256_final(&outer, output); 46 } 47 48 void hmac_sha2_256(const bytebuffer key, const bytebuffer msg, bytebuffer output) { 49 static const size_t block_size = 32; 50 assert(key.len == block_size); 51 assert(output.len == block_size); 52 53 dbg_print_bb1("HMAC key", key); 54 dbg_print_bb1("HMAC message", msg); 55 hmac_sha256(key.data, key.len, msg.data, msg.len, output.data); 56 dbg_print_bb1("HMAC output", output); 57 } 58