3 * implementation of HMAC as described in RFC2104
10 * hmac = hash ( k^opad , hash( k^ipad , msg))
21 typedef sha256_ctx_t hmac_sha256_ctx_t;
23 #ifndef HMAC_SHORTONLY
25 void hmac_sha256_init(hmac_sha256_ctx_t *s, void* key, uint16_t kl){
26 uint8_t buffer[SHA256_BLOCK_BITS/8];
29 if (kl > SHA256_BLOCK_BITS){
30 sha256((void*)buffer, key, kl);
32 memcpy(buffer, key, (kl+7)/8);
35 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
40 sha256_nextBlock(s, buffer);
41 #if defined SECURE_WIPE_BUFFER
42 memset(buffer, 0, SHA256_BLOCK_BITS/8);
46 void hmac_sha256_final(hmac_sha256_ctx_t *s, void* key, uint16_t kl){
47 uint8_t buffer[SHA256_BLOCK_BITS/8];
51 if (kl > SHA256_BLOCK_BITS){
52 sha256((void*)buffer, key, kl);
54 memcpy(buffer, key, (kl+7)/8);
57 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
62 sha256_nextBlock(&a, buffer); /* hash key ^ opad */
63 sha256_ctx2hash((void*)buffer, s); /* copy hash(key ^ ipad, msg) to buffer */
64 sha256_lastBlock(s, buffer, SHA256_HASH_BITS);
65 #if defined SECURE_WIPE_BUFFER
66 memset(buffer, 0, SHA256_BLOCK_BITS/8);
74 void hmac_sha256_nextBlock()
75 void hmac_sha256_lastBlock()
80 * message length in bits!
82 void hmac_sha256(void* dest, void* key, uint16_t kl, void* msg, uint64_t ml){ /* a one-shot*/
85 uint8_t buffer[SHA256_BLOCK_BITS/8];
87 memset(buffer, 0, SHA256_BLOCK_BITS/8);
89 /* if key is larger than a block we have to hash it*/
90 if (kl > SHA256_BLOCK_BITS){
91 sha256((void*)buffer, key, kl);
93 memcpy(buffer, key, (kl+7)/8);
96 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
100 sha256_nextBlock(&s, buffer);
101 while (ml >= SHA256_BLOCK_BITS){
102 sha256_nextBlock(&s, msg);
103 msg = (uint8_t*)msg + SHA256_BLOCK_BITS/8;
104 ml -= SHA256_BLOCK_BITS;
106 sha256_lastBlock(&s, msg, ml);
107 /* since buffer still contains key xor ipad we can do ... */
108 for (i=0; i<SHA256_BLOCK_BITS/8; ++i){
109 buffer[i] ^= IPAD ^ OPAD;
111 sha256_ctx2hash(dest, &s); /* save inner hash temporary to dest */
113 sha256_nextBlock(&s, buffer);
114 sha256_lastBlock(&s, dest, SHA256_HASH_BITS);
115 sha256_ctx2hash(dest, &s);