xref: /onnv-gate/usr/src/lib/libldap4/sec/cram_md5.c (revision 0:68f95e015346)
1*0Sstevel@tonic-gate /*
2*0Sstevel@tonic-gate  *
3*0Sstevel@tonic-gate  * Copyright %G% Sun Microsystems, Inc.
4*0Sstevel@tonic-gate  * All Rights Reserved
5*0Sstevel@tonic-gate  *
6*0Sstevel@tonic-gate  *
7*0Sstevel@tonic-gate  * Comments:
8*0Sstevel@tonic-gate  *
9*0Sstevel@tonic-gate  */
10*0Sstevel@tonic-gate 
11*0Sstevel@tonic-gate #pragma ident	"%Z%%M%	%I%	%E% SMI"
12*0Sstevel@tonic-gate 
13*0Sstevel@tonic-gate #include <sys/types.h>
14*0Sstevel@tonic-gate #include <strings.h>
15*0Sstevel@tonic-gate #include "sec.h"
16*0Sstevel@tonic-gate 
17*0Sstevel@tonic-gate /* text is the challenge, key is the password, digest is an allocated
18*0Sstevel@tonic-gate    buffer (min 16 chars) which will contain the resulting digest */
19*0Sstevel@tonic-gate void hmac_md5(unsigned char *text, int text_len, unsigned char *key,
20*0Sstevel@tonic-gate 	int key_len, unsigned char *digest)
21*0Sstevel@tonic-gate {
22*0Sstevel@tonic-gate 	MD5_CTX context;
23*0Sstevel@tonic-gate 	unsigned char k_ipad[65];
24*0Sstevel@tonic-gate 	unsigned char k_opad[65];
25*0Sstevel@tonic-gate 	unsigned char tk[16];
26*0Sstevel@tonic-gate 	int i;
27*0Sstevel@tonic-gate 
28*0Sstevel@tonic-gate 	if (key_len > 64){
29*0Sstevel@tonic-gate 		MD5_CTX tctx;
30*0Sstevel@tonic-gate 
31*0Sstevel@tonic-gate 		(void) MD5Init(&tctx);
32*0Sstevel@tonic-gate 		(void) MD5Update(&tctx, key, key_len);
33*0Sstevel@tonic-gate 		(void) MD5Final(tk, &tctx);
34*0Sstevel@tonic-gate 		key = tk;
35*0Sstevel@tonic-gate 		key_len = 16;
36*0Sstevel@tonic-gate 	}
37*0Sstevel@tonic-gate 
38*0Sstevel@tonic-gate 	bzero(k_ipad, sizeof (k_ipad));
39*0Sstevel@tonic-gate 	bzero(k_opad, sizeof (k_opad));
40*0Sstevel@tonic-gate 	bcopy(key, k_ipad, key_len);
41*0Sstevel@tonic-gate 	bcopy(key, k_opad, key_len);
42*0Sstevel@tonic-gate 
43*0Sstevel@tonic-gate 	for (i=0; i<64; i++){
44*0Sstevel@tonic-gate 		k_ipad[i] ^= 0x36;
45*0Sstevel@tonic-gate 		k_opad[i] ^= 0x5c;
46*0Sstevel@tonic-gate 	}
47*0Sstevel@tonic-gate 
48*0Sstevel@tonic-gate 	/* Perform inner MD5 */
49*0Sstevel@tonic-gate 	(void) MD5Init(&context);
50*0Sstevel@tonic-gate 	(void) MD5Update(&context, k_ipad, 64);
51*0Sstevel@tonic-gate 	(void) MD5Update(&context, text, text_len);
52*0Sstevel@tonic-gate 	(void) MD5Final(digest, &context);
53*0Sstevel@tonic-gate 
54*0Sstevel@tonic-gate 	/* Perform outer MD5 */
55*0Sstevel@tonic-gate 	(void) MD5Init(&context);
56*0Sstevel@tonic-gate 	(void) MD5Update(&context, k_opad, 64);
57*0Sstevel@tonic-gate 	(void) MD5Update(&context, digest, 16);
58*0Sstevel@tonic-gate 
59*0Sstevel@tonic-gate 	(void) MD5Final(digest, &context);
60*0Sstevel@tonic-gate 
61*0Sstevel@tonic-gate 	return;
62*0Sstevel@tonic-gate }
63