2 * Copyright (C) 2004 Internet Systems Consortium, Inc. ("ISC")
3 * Copyright (C) 2000, 2001 Internet Software Consortium.
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 * PERFORMANCE OF THIS SOFTWARE.
18 /* $Id: hmacmd5.c,v 1.5.2.1 2004/03/09 06:11:46 marka Exp $ */
21 * This code implements the HMAC-MD5 keyed hash algorithm
22 * described in RFC 2104.
27 #include <isc/assertions.h>
28 #include <isc/hmacmd5.h>
30 #include <isc/string.h>
31 #include <isc/types.h>
39 * Start HMAC-MD5 process. Initialize an md5 context and digest the key.
42 isc_hmacmd5_init(isc_hmacmd5_t *ctx, const unsigned char *key,
45 unsigned char ipad[PADLEN];
48 memset(ctx->key, 0, sizeof (ctx->key));
49 if (len > sizeof(ctx->key)) {
51 isc_md5_init(&md5ctx);
52 isc_md5_update(&md5ctx, key, len);
53 isc_md5_final(&md5ctx, ctx->key);
55 memcpy(ctx->key, key, len);
57 isc_md5_init(&ctx->md5ctx);
58 memset(ipad, IPAD, sizeof (ipad));
59 for (i = 0; i < PADLEN; i++)
60 ipad[i] ^= ctx->key[i];
61 isc_md5_update(&ctx->md5ctx, ipad, sizeof(ipad));
65 isc_hmacmd5_invalidate(isc_hmacmd5_t *ctx) {
66 isc_md5_invalidate(&ctx->md5ctx);
67 memset(ctx->key, 0, sizeof (ctx->key));
68 memset(ctx, 0, sizeof (ctx));
72 * Update context to reflect the concatenation of another buffer full
76 isc_hmacmd5_update(isc_hmacmd5_t *ctx, const unsigned char *buf,
79 isc_md5_update(&ctx->md5ctx, buf, len);
83 * Compute signature - finalize MD5 operation and reapply MD5.
86 isc_hmacmd5_sign(isc_hmacmd5_t *ctx, unsigned char *digest) {
87 unsigned char opad[PADLEN];
90 isc_md5_final(&ctx->md5ctx, digest);
92 memset(opad, OPAD, sizeof (opad));
93 for (i = 0; i < PADLEN; i++)
94 opad[i] ^= ctx->key[i];
96 isc_md5_init(&ctx->md5ctx);
97 isc_md5_update(&ctx->md5ctx, opad, sizeof(opad));
98 isc_md5_update(&ctx->md5ctx, digest, ISC_MD5_DIGESTLENGTH);
99 isc_md5_final(&ctx->md5ctx, digest);
100 isc_hmacmd5_invalidate(ctx);
104 * Verify signature - finalize MD5 operation and reapply MD5, then
105 * compare to the supplied digest.
108 isc_hmacmd5_verify(isc_hmacmd5_t *ctx, unsigned char *digest) {
109 unsigned char newdigest[ISC_MD5_DIGESTLENGTH];
111 isc_hmacmd5_sign(ctx, newdigest);
112 return (ISC_TF(memcmp(digest, newdigest, ISC_MD5_DIGESTLENGTH) == 0));