4 * This file is part of BeRTOS.
6 * Bertos 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 2 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, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * As a special exception, you may use this file as part of a free software
21 * library without restriction. Specifically, if other files instantiate
22 * templates or use macros or inline functions from this file, or you compile
23 * this file and link it with other files to produce an executable, this
24 * file does not by itself cause the resulting executable to be covered by
25 * the GNU General Public License. This exception does not however
26 * invalidate any other reasons why the executable file might be covered by
27 * the GNU General Public License.
29 * Copyright 2010 Develer S.r.l. (http://www.develer.com/)
33 * \brief HMAC implementation
34 * \author Giovanni Bajo <rasky@develer.com>
43 static void HMAC_set_key(Mac *m, const uint8_t *key, size_t key_len)
45 HMAC_Context *ctx = (HMAC_Context *)m;
47 memset(ctx->key, 0, ctx->m.key_len);
48 if (key_len <= ctx->m.key_len)
49 memcpy(ctx->key, key, key_len);
53 hash_update(ctx->h, key, key_len);
54 memcpy(ctx->key, hash_final(ctx->h), hash_digest_len(ctx->h));
57 xor_block_const(ctx->key, ctx->key, 0x5C, ctx->m.key_len);
60 static void HMAC_begin(Mac *m)
62 HMAC_Context *ctx = (HMAC_Context *)m;
63 int klen = ctx->m.key_len;
65 xor_block_const(ctx->key, ctx->key, 0x36^0x5C, klen);
67 hash_update(ctx->h, ctx->key, klen);
70 static void HMAC_update(Mac *m, const uint8_t *data, size_t len)
72 HMAC_Context *ctx = (HMAC_Context *)m;
73 hash_update(ctx->h, data, len);
76 static uint8_t *HMAC_final(Mac *m)
78 HMAC_Context *ctx = (HMAC_Context *)m;
79 int hlen = hash_digest_len(ctx->h);
82 memcpy(temp, hash_final(ctx->h), hlen);
84 xor_block_const(ctx->key, ctx->key, 0x5C^0x36, ctx->m.key_len);
86 hash_update(ctx->h, ctx->key, ctx->m.key_len);
87 hash_update(ctx->h, temp, hlen);
90 return hash_final(ctx->h);
93 /*********************************************************************/
95 void HMAC_init(HMAC_Context *ctx, Hash *h)
98 ctx->m.key_len = hash_block_len(h);
99 ctx->m.digest_len = hash_digest_len(h);
100 ctx->m.set_key = HMAC_set_key;
101 ctx->m.begin = HMAC_begin;
102 ctx->m.update = HMAC_update;
103 ctx->m.final = HMAC_final;
104 ASSERT(sizeof(ctx->key) >= ctx->m.key_len);