4 * digest support for NTP, MD5 and with OpenSSL more
11 #include "ntp_string.h"
12 #include "ntp_stdlib.h"
15 #include "openssl/evp.h"
21 * MD5authencrypt - generate message digest
23 * Returns length of MAC including key ID and digest.
27 int type
, /* hash algorithm */
28 u_char
*key
, /* key pointer */
29 u_int32
*pkt
, /* packet pointer */
30 int length
/* packet length */
33 u_char digest
[EVP_MAX_MD_SIZE
];
42 * Compute digest of key concatenated with packet. Note: the
43 * key type and digest type have been verified when the key
48 EVP_DigestInit(&ctx
, EVP_get_digestbynid(type
));
49 EVP_DigestUpdate(&ctx
, key
, (u_int
)cache_keylen
);
50 EVP_DigestUpdate(&ctx
, (u_char
*)pkt
, (u_int
)length
);
51 EVP_DigestFinal(&ctx
, digest
, &len
);
54 MD5Update(&md5
, key
, (u_int
)cache_keylen
);
55 MD5Update(&md5
, (u_char
*)pkt
, (u_int
)length
);
56 MD5Final(digest
, &md5
);
59 memmove((u_char
*)pkt
+ length
+ 4, digest
, len
);
65 * MD5authdecrypt - verify MD5 message authenticator
67 * Returns one if digest valid, zero if invalid.
71 int type
, /* hash algorithm */
72 u_char
*key
, /* key pointer */
73 u_int32
*pkt
, /* packet pointer */
74 int length
, /* packet length */
75 int size
/* MAC size */
78 u_char digest
[EVP_MAX_MD_SIZE
];
87 * Compute digest of key concatenated with packet. Note: the
88 * key type and digest type have been verified when the key
93 EVP_DigestInit(&ctx
, EVP_get_digestbynid(type
));
94 EVP_DigestUpdate(&ctx
, key
, (u_int
)cache_keylen
);
95 EVP_DigestUpdate(&ctx
, (u_char
*)pkt
, (u_int
)length
);
96 EVP_DigestFinal(&ctx
, digest
, &len
);
99 MD5Update(&md5
, key
, (u_int
)cache_keylen
);
100 MD5Update(&md5
, (u_char
*)pkt
, (u_int
)length
);
101 MD5Final(digest
, &md5
);
104 if ((u_int
)size
!= len
+ 4) {
106 "MAC decrypt: MAC length error");
109 return (!memcmp(digest
, (char *)pkt
+ length
+ 4, len
));
113 * Calculate the reference id from the address. If it is an IPv4
114 * address, use it as is. If it is an IPv6 address, do a md5 on
115 * it and use the bottom 4 bytes.
118 addr2refid(sockaddr_u
*addr
)
130 return (NSRCADR(addr
));
134 EVP_DigestInit(&ctx
, EVP_get_digestbynid(NID_md5
));
135 EVP_DigestUpdate(&ctx
, (u_char
*)PSOCK_ADDR6(addr
),
136 sizeof(struct in6_addr
));
137 EVP_DigestFinal(&ctx
, digest
, &len
);
140 MD5Update(&md5
, (u_char
*)PSOCK_ADDR6(addr
),
141 sizeof(struct in6_addr
));
142 MD5Final(digest
, &md5
);
144 memcpy(&addr_refid
, digest
, 4);