xref: /freebsd/contrib/ntp/libntp/a_md5encrypt.c (revision ae83180158c4c937f170e31eff311b18c0286a93)
1 /*
2  *	MD5 interface for rsaref2.0
3  *
4  * These routines implement an interface for the RSA Laboratories
5  * implementation of the Message Digest 5 (MD5) algorithm. This
6  * algorithm is included in the rsaref2.0 package available from RSA in
7  * the US and foreign countries. Further information is available at
8  * www.rsa.com.
9  */
10 
11 #include "ntp_machine.h"
12 
13 #ifdef HAVE_CONFIG_H
14 #include <config.h>
15 #endif
16 
17 #include <stdio.h>
18 
19 #include "ntp_types.h"
20 #include "ntp_string.h"
21 #include "global.h"
22 #include "md5.h"
23 #include "ntp_stdlib.h"
24 
25 #define BLOCK_OCTETS	16	/* message digest size */
26 
27 
28 /*
29  * MD5authencrypt - generate MD5 message authenticator
30  *
31  * Returns length of authenticator field.
32  */
33 int
34 MD5authencrypt(
35 	u_char *key,		/* key pointer */
36 	u_int32 *pkt,		/* packet pointer */
37 	int length		/* packet length */
38 	)
39 {
40 	MD5_CTX ctx;
41 	u_char digest[BLOCK_OCTETS];
42 	int i;
43 
44 	/*
45 	 * MD5 with key identifier concatenated with packet.
46 	 */
47 	MD5Init(&ctx);
48 	MD5Update(&ctx, key, (u_int)cache_keylen);
49 	MD5Update(&ctx, (u_char *)pkt, (u_int)length);
50 	MD5Final(digest, &ctx);
51 	i = length / 4;
52 	memmove((char *)&pkt[i + 1], (char *)digest, BLOCK_OCTETS);
53 	return (BLOCK_OCTETS + 4);
54 }
55 
56 
57 /*
58  * MD5authdecrypt - verify MD5 message authenticator
59  *
60  * Returns one if authenticator valid, zero if invalid.
61  */
62 int
63 MD5authdecrypt(
64 	u_char *key,		/* key pointer */
65 	u_int32 *pkt,		/* packet pointer */
66 	int length, 	/* packet length */
67 	int size		/* MAC size */
68 	)
69 {
70 	MD5_CTX ctx;
71 	u_char digest[BLOCK_OCTETS];
72 
73 	/*
74 	 * MD5 with key identifier concatenated with packet.
75 	 */
76 	if (size != BLOCK_OCTETS + 4)
77 		return (0);
78 	MD5Init(&ctx);
79 	MD5Update(&ctx, key, (u_int)cache_keylen);
80 	MD5Update(&ctx, (u_char *)pkt, (u_int)length);
81 	MD5Final(digest, &ctx);
82 	return (!memcmp((char *)digest, (char *)pkt + length + 4,
83 		BLOCK_OCTETS));
84 }
85