Fix.
[shishi.git] / crypto / hmac.c
blob5ffae38bc24bf9c9fd495991995bdaf2fee5a226
1 /* hmac.c
3 * HMAC message authentication code (RFC-2104).
4 */
6 /* nettle, low-level cryptographics library
8 * Copyright (C) 2001 Niels Möller
9 *
10 * The nettle library is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or (at your
13 * option) any later version.
15 * The nettle library is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
18 * License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with the nettle library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23 * MA 02111-1307, USA.
26 #if HAVE_CONFIG_H
27 # include "config.h"
28 #endif
30 #include <assert.h>
31 #include <string.h>
33 #include "hmac.h"
35 #include "memxor.h"
37 #define IPAD 0x36
38 #define OPAD 0x5c
40 void
41 hmac_set_key(void *outer, void *inner, void *state,
42 const struct nettle_hash *hash,
43 unsigned key_length, const uint8_t *key)
45 uint8_t *pad = alloca(hash->block_size);
47 hash->init(outer);
48 hash->init(inner);
50 if (key_length > hash->block_size)
52 /* Reduce key to the algorithm's hash size. Use the area pointed
53 * to by state for the temporary state. */
55 uint8_t *digest = alloca(hash->digest_size);
57 hash->init(state);
58 hash->update(state, key_length, key);
59 hash->digest(state, hash->digest_size, digest);
61 key = digest;
62 key_length = hash->digest_size;
65 assert(key_length <= hash->block_size);
67 memset(pad, OPAD, hash->block_size);
68 memxor(pad, key, key_length);
70 hash->update(outer, hash->block_size, pad);
72 memset(pad, IPAD, hash->block_size);
73 memxor(pad, key, key_length);
75 hash->update(inner, hash->block_size, pad);
77 memcpy(state, inner, hash->context_size);
80 void
81 hmac_update(void *state,
82 const struct nettle_hash *hash,
83 unsigned length, const uint8_t *data)
85 hash->update(state, length, data);
88 void
89 hmac_digest(const void *outer, const void *inner, void *state,
90 const struct nettle_hash *hash,
91 unsigned length, uint8_t *dst)
93 uint8_t *digest = alloca(hash->digest_size);
95 hash->digest(state, hash->digest_size, digest);
97 memcpy(state, outer, hash->context_size);
99 hash->update(state, hash->digest_size, digest);
100 hash->digest(state, length, dst);
102 memcpy(state, inner, hash->context_size);