3 * implementation of HMAC as described in RFC2104
10 * hmac = hash ( k^opad , hash( k^ipad , msg))
20 typedef sha256_ctx_t hmac_sha256_ctx_t;
22 void hmac_sha256_init(hmac_sha256_ctx_t *s, void* key, uint16_t kl){
23 uint8_t buffer[SHA256_BLOCK_BITS/8];
26 if (kl > SHA256_BLOCK_BITS){
27 sha256((void*)buffer, key, kl);
29 memcpy(buffer, key, kl/8 + (kl & 0x7)?1:0);
32 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
37 sha256_nextBlock(s, buffer);
38 #if defined SECURE_WIPE_BUFFER
39 memset(buffer, 0, SHA256_BLOCK_BITS/8);
43 void hmac_sha256_final(hmac_sha256_ctx_t *s, void* key, uint16_t kl){
44 uint8_t buffer[SHA256_BLOCK_BITS/8];
48 if (kl > SHA256_BLOCK_BITS){
49 sha256((void*)buffer, key, kl);
51 memcpy(buffer, key, kl/8 + (kl & 0x7)?1:0);
54 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
59 sha256_nextBlock(&a, buffer); /* hash key ^ opad */
60 sha256_ctx2hash((void*)buffer, s); /* copy hash(key ^ ipad, msg) to buffer */
61 sha256_lastBlock(s, buffer, SHA256_HASH_BITS);
62 #if defined SECURE_WIPE_BUFFER
63 memset(buffer, 0, SHA256_BLOCK_BITS/8);
69 void hmac_sha256_nextBlock()
70 void hmac_sha256_lastBlock()
75 * message length in bits!
77 void hmac_sha256(void* dest, void* key, uint16_t kl, void* msg, uint64_t ml){ /* a one-shot*/
80 uint8_t buffer[SHA256_BLOCK_BITS/8];
82 /* if key is larger than a block we have to hash it*/
83 if (kl > SHA256_BLOCK_BITS){
84 sha256((void*)buffer, key, kl);
86 memcpy(buffer, key, kl/8 + (kl & 0x7)?1:0);
89 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
93 sha256_nextBlock(&s, buffer);
94 while (ml >= SHA256_BLOCK_BITS){
95 sha256_nextBlock(&s, msg);
96 msg += SHA256_BLOCK_BITS/8;
97 ml -= SHA256_BLOCK_BITS;
99 sha256_lastBlock(&s, msg, ml);
100 /* since buffer still contains key xor ipad we can do ... */
101 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
102 buffer[i] ^= IPAD ^ OPAD;
104 sha265_ctx2hash(dest, &s); /* save inner hash temporary to dest */
106 sha256_nextBlock(&s, buffer);
107 sha256_lastBlock(&s, dest, SHA256_HASH_BITS);
108 sha265_ctx2hash(dest, &s);