xref: /openbsd-src/sys/lib/libsa/hmac_sha1.c (revision eea83730682e8cff9c141d1ef884b5560a3aa6af)
1 /*	$OpenBSD: hmac_sha1.c,v 1.1 2012/10/09 12:36:50 jsing Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008 Damien Bergamini <damien.bergamini@free.fr>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/param.h>
20 
21 #include <lib/libsa/stand.h>
22 
23 #include "hmac_sha1.h"
24 
25 /*
26  * HMAC-SHA-1 (from RFC 2202).
27  */
28 void
hmac_sha1(const u_int8_t * text,size_t text_len,const u_int8_t * key,size_t key_len,u_int8_t digest[SHA1_DIGEST_LENGTH])29 hmac_sha1(const u_int8_t *text, size_t text_len, const u_int8_t *key,
30     size_t key_len, u_int8_t digest[SHA1_DIGEST_LENGTH])
31 {
32 	SHA1_CTX ctx;
33 	u_int8_t k_pad[SHA1_BLOCK_LENGTH];
34 	u_int8_t tk[SHA1_DIGEST_LENGTH];
35 	int i;
36 
37 	if (key_len > SHA1_BLOCK_LENGTH) {
38 		SHA1Init(&ctx);
39 		SHA1Update(&ctx, key, key_len);
40 		SHA1Final(tk, &ctx);
41 
42 		key = tk;
43 		key_len = SHA1_DIGEST_LENGTH;
44 	}
45 
46 	bzero(k_pad, sizeof k_pad);
47 	bcopy(key, k_pad, key_len);
48 	for (i = 0; i < SHA1_BLOCK_LENGTH; i++)
49 		k_pad[i] ^= 0x36;
50 
51 	SHA1Init(&ctx);
52 	SHA1Update(&ctx, k_pad, SHA1_BLOCK_LENGTH);
53 	SHA1Update(&ctx, text, text_len);
54 	SHA1Final(digest, &ctx);
55 
56 	bzero(k_pad, sizeof k_pad);
57 	bcopy(key, k_pad, key_len);
58 	for (i = 0; i < SHA1_BLOCK_LENGTH; i++)
59 		k_pad[i] ^= 0x5c;
60 
61 	SHA1Init(&ctx);
62 	SHA1Update(&ctx, k_pad, SHA1_BLOCK_LENGTH);
63 	SHA1Update(&ctx, digest, SHA1_DIGEST_LENGTH);
64 	SHA1Final(digest, &ctx);
65 }
66