2 * HMAC-SHA1 Message Authentication Code (RFC 2202)
4 * (c) 2008--2009 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
16 sha1_hmac_init(sha1_hmac_context *hd, const byte *key, uint keylen)
18 byte keybuf[SHA1_BLOCK_SIZE], buf[SHA1_BLOCK_SIZE];
20 // Hash the key if necessary
21 if (keylen <= SHA1_BLOCK_SIZE)
23 memcpy(keybuf, key, keylen);
24 bzero(keybuf + keylen, SHA1_BLOCK_SIZE - keylen);
28 sha1_hash_buffer(keybuf, key, keylen);
29 bzero(keybuf + SHA1_SIZE, SHA1_BLOCK_SIZE - SHA1_SIZE);
32 // Initialize the inner digest
34 for (int i=0; i < SHA1_BLOCK_SIZE; i++)
35 buf[i] = keybuf[i] ^ 0x36;
36 sha1_update(&hd->ictx, buf, SHA1_BLOCK_SIZE);
38 // Initialize the outer digest
40 for (int i=0; i < SHA1_BLOCK_SIZE; i++)
41 buf[i] = keybuf[i] ^ 0x5c;
42 sha1_update(&hd->octx, buf, SHA1_BLOCK_SIZE);
46 sha1_hmac_update(sha1_hmac_context *hd, const byte *data, uint datalen)
48 // Just update the inner digest
49 sha1_update(&hd->ictx, data, datalen);
52 byte *sha1_hmac_final(sha1_hmac_context *hd)
54 // Finish the inner digest
55 byte *isha = sha1_final(&hd->ictx);
57 // Finish the outer digest
58 sha1_update(&hd->octx, isha, SHA1_SIZE);
59 return sha1_final(&hd->octx);
63 sha1_hmac(byte *outbuf, const byte *key, uint keylen, const byte *data, uint datalen)
66 sha1_hmac_init(&hd, key, keylen);
67 sha1_hmac_update(&hd, data, datalen);
68 byte *osha = sha1_hmac_final(&hd);
69 memcpy(outbuf, osha, SHA1_SIZE);
75 #include <ucw/string.h>
77 static uint rd(char *dest)
80 if (!fgets(buf, sizeof(buf), stdin))
82 *strchr(buf, '\n') = 0;
83 if (buf[0] == '0' && buf[1] == 'x')
85 const char *e = hex_to_mem(dest, buf+2, 1024, 0);
98 char key[1024], data[1024];
102 sha1_hmac(hmac, key, kl, data, dl);
103 mem_to_hex(data, hmac, SHA1_SIZE, 0);