3 This file is part of the AVR-Crypto-Lib.
4 Copyright (C) 2009 Daniel Otte (daniel.otte@rub.de)
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * implementation of HMAC as described in RFC2104
23 * email: daniel.otte@rub.de
24 * License: GPLv3 or later
28 * hmac = hash ( k^opad , hash( k^ipad , msg))
40 #ifndef HMAC_SHORTONLY
42 void hmac_md5_init(hmac_md5_ctx_t *s, void *key, uint16_t keylength_b){
43 uint8_t buffer[MD5_BLOCK_BYTES];
46 memset(buffer, 0, MD5_BLOCK_BYTES);
47 if (keylength_b > MD5_BLOCK_BITS){
48 md5((void*)buffer, key, keylength_b);
50 memcpy(buffer, key, (keylength_b+7)/8);
53 for (i=0; i<MD5_BLOCK_BYTES; ++i){
57 md5_nextBlock(&(s->a), buffer);
59 for (i=0; i<MD5_BLOCK_BYTES; ++i){
60 buffer[i] ^= IPAD^OPAD;
63 md5_nextBlock(&(s->b), buffer);
65 #if defined SECURE_WIPE_BUFFER
66 memset(buffer, 0, MD5_BLOCK_BYTES);
70 void hmac_md5_nextBlock(hmac_md5_ctx_t *s, const void *block){
71 md5_nextBlock(&(s->a), block);
74 void hmac_md5_lastBlock(hmac_md5_ctx_t *s, const void *block, uint16_t length_b){
75 md5_lastBlock(&(s->a), block, length_b);
78 void hmac_md5_final(void *dest, hmac_md5_ctx_t *s){
79 md5_ctx2hash((md5_hash_t*)dest, &(s->a));
80 md5_lastBlock(&(s->b), dest, MD5_HASH_BITS);
81 md5_ctx2hash((md5_hash_t*)dest, &(s->b));
87 void hmac_md5_nextBlock()
88 void hmac_md5_lastBlock()
93 * message length in bits!
95 void hmac_md5(void *dest, void *key, uint16_t keylength_b, void *msg, uint32_t msglength_b){ /* a one-shot*/
98 uint8_t buffer[MD5_BLOCK_BYTES];
100 memset(buffer, 0, MD5_BLOCK_BYTES);
102 /* if key is larger than a block we have to hash it*/
103 if (keylength_b > MD5_BLOCK_BITS){
104 md5((void*)buffer, key, keylength_b);
106 memcpy(buffer, key, (keylength_b+7)/8);
109 for (i=0; i<MD5_BLOCK_BYTES; ++i){
113 md5_nextBlock(&s, buffer);
114 while (msglength_b >= MD5_BLOCK_BITS){
115 md5_nextBlock(&s, msg);
116 msg = (uint8_t*)msg + MD5_BLOCK_BYTES;
117 msglength_b -= MD5_BLOCK_BITS;
119 md5_lastBlock(&s, msg, msglength_b);
120 /* since buffer still contains key xor ipad we can do ... */
121 for (i=0; i<MD5_BLOCK_BYTES; ++i){
122 buffer[i] ^= IPAD ^ OPAD;
124 md5_ctx2hash(dest, &s); /* save inner hash temporary to dest */
126 md5_nextBlock(&s, buffer);
127 md5_lastBlock(&s, dest, MD5_HASH_BITS);
128 md5_ctx2hash(dest, &s);