Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / ntp / libntp / authparity.c
1 /*
2  * auth_parity - set parity on a key/check for odd parity
3  */
4
5 #ifdef HAVE_CONFIG_H
6 # include <config.h>
7 #endif
8
9 #ifdef DES
10 #include "ntp_stdlib.h"
11
12 int
13 DESauth_parity(
14         u_int32 *key
15         )
16 {
17         u_int32 mask;
18         int parity_err;
19         int bitcount;
20         int half;
21         int byte;
22         int i;
23
24         /*
25          * Go through counting bits in each byte.  Check to see if
26          * each parity bit was set correctly.  If not, note the error
27          * and set it right.
28          */
29         parity_err = 0;
30         for (half = 0; half < 2; half++) {              /* two halves of key */
31                 mask = 0x80000000;
32                 for (byte = 0; byte < 4; byte++) {      /* 4 bytes per half */
33                         bitcount = 0;
34                         for (i = 0; i < 7; i++) {       /* 7 data bits / byte */
35                                 if (key[half] & mask)
36                                     bitcount++;
37                                 mask >>= 1;
38                         }
39
40                         /*
41                          * If bitcount is even, parity must be set.  If
42                          * bitcount is odd, parity must be clear.
43                          */
44                         if ((bitcount & 0x1) == 0) {
45                                 if (!(key[half] & mask)) {
46                                         parity_err++;
47                                         key[half] |= mask;
48                                 }
49                         } else {
50                                 if (key[half] & mask) {
51                                         parity_err++;
52                                         key[half] &= ~mask;
53                                 }
54                         }
55                         mask >>= 1;
56                 }
57         }
58
59         /*
60          * Return the result of the parity check.
61          */
62         return (parity_err == 0);
63 }
64 #else
65 int authparity_bs;
66 #endif /* DES */