Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / ntp / libntp / authencrypt.c
1 /*
2  * DES interface for rsaref2.0
3  *
4  * These routines implement an interface for the RSA Laboratories
5  * implementation of the Data Encryption Standard (DES) algorithm
6  * operating in Cipher-Block Chaining (CBC) mode. This algorithm is
7  * included in the rsaref2.0 package available from RSA in the US and
8  * foreign countries. Further information is available at www.rsa.com.
9  */
10
11 #include "ntp_machine.h"
12
13 #ifdef HAVE_CONFIG_H
14 #include <config.h>
15 #endif
16
17 #ifdef DES
18 #include "ntp_types.h"
19 #include "ntp_fp.h"
20 #include "ntp_string.h"
21 #include "global.h"
22 #include "des.h"
23 #include "ntp_stdlib.h"
24
25 #define BLOCK_OCTETS    8       /* message digest size */
26 #define MAXTPKT         128 /* max packet size */
27
28
29 /*
30  * DESauthencrypt - generate DES-CBC message authenticator
31  *
32  * Returns length of authenticator field.
33  */
34 int
35 DESauthencrypt(
36         u_char *key,            /* key pointer */
37         u_int32 *pkt,           /* packet pointer */
38         int length              /* packet length */
39         )
40 {
41         DES_CBC_CTX ctx;
42         u_int32 tpkt[MAXTPKT];
43         u_int32 work[2];
44         int i, j;
45
46         /*
47          * DES-CBC with zero IV. Note the encrypted text is discarded.
48          */
49         work[0] = work[1] = 0;
50         DES_CBCInit(&ctx, key, (u_char *)work, 1);
51         DES_CBCUpdate(&ctx, (u_char *)tpkt, (u_char *)pkt,
52                 (u_int)length);
53         i = length / 4 + 1;
54         j = i - 3;
55         pkt[i++] = (u_int32)htonl(tpkt[j++]);
56         pkt[i] = (u_int32)htonl(tpkt[j]);
57         return (BLOCK_OCTETS + 4);
58 }
59
60
61 /*
62  * DESauthdecrypt - verify DES message authenticator
63  *
64  * Returns one if authenticator valid, zero if invalid.
65  */
66 int
67 DESauthdecrypt(
68         u_char *key,            /* key pointer */
69         u_int32 *pkt,           /* packet pointer */
70         int length,             /* packet length */
71         int size                /* size of MAC field */
72         )
73 {
74         DES_CBC_CTX ctx;
75         u_int32 tpkt[MAXTPKT];
76         u_int32 work[2];
77         int i, j;
78
79         /*
80          * DES-CBC with zero IV. Note the encrypted text is discarded.
81          */
82         if (size != BLOCK_OCTETS + 4)
83                 return (0);
84         work[0] = work[1] = 0;
85         DES_CBCInit (&ctx, key, (u_char *)work, 1);
86         DES_CBCUpdate (&ctx, (u_char *)tpkt, (u_char *)pkt,
87                 (u_int)length);
88         i = length / 4 + 1;
89         j = i - 3;
90         if ((u_int32)ntohl(pkt[i++]) == tpkt[j++] &&
91                 (u_int32)ntohl(pkt[i]) == tpkt[j])
92                 return (1);
93         return (0);
94 }
95 #else
96 int authencrypt_bs;
97 #endif /* DES */