/contrib/ntp/libntp/a_md5encrypt.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 104 lines · 59 code · 12 blank · 33 comment · 4 complexity · f9463644b248d75bafdd70556cd13c5b MD5 · raw file

  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. #ifdef HAVE_CONFIG_H
  11. #include <config.h>
  12. #endif
  13. #include "ntp_fp.h"
  14. #include "ntp_string.h"
  15. #include "ntp_stdlib.h"
  16. /* Disable the openssl md5 includes, because they'd clash with ours. */
  17. /* #define NO_MD5 */
  18. /* #define OPENSSL_NO_MD5 */
  19. #undef OPENSSL
  20. #include "ntp.h"
  21. #include "global.h"
  22. #include "ntp_md5.h"
  23. /*
  24. * MD5authencrypt - generate MD5 message authenticator
  25. *
  26. * Returns length of authenticator field.
  27. */
  28. int
  29. MD5authencrypt(
  30. u_char *key, /* key pointer */
  31. u_int32 *pkt, /* packet pointer */
  32. int length /* packet length */
  33. )
  34. {
  35. MD5_CTX md5;
  36. u_char digest[16];
  37. /*
  38. * MD5 with key identifier concatenated with packet.
  39. */
  40. MD5Init(&md5);
  41. MD5Update(&md5, key, (u_int)cache_keylen);
  42. MD5Update(&md5, (u_char *)pkt, (u_int)length);
  43. MD5Final(digest, &md5);
  44. memmove((u_char *)pkt + length + 4, digest, 16);
  45. return (16 + 4);
  46. }
  47. /*
  48. * MD5authdecrypt - verify MD5 message authenticator
  49. *
  50. * Returns one if authenticator valid, zero if invalid.
  51. */
  52. int
  53. MD5authdecrypt(
  54. u_char *key, /* key pointer */
  55. u_int32 *pkt, /* packet pointer */
  56. int length, /* packet length */
  57. int size /* MAC size */
  58. )
  59. {
  60. MD5_CTX md5;
  61. u_char digest[16];
  62. /*
  63. * MD5 with key identifier concatenated with packet.
  64. */
  65. MD5Init(&md5);
  66. MD5Update(&md5, key, (u_int)cache_keylen);
  67. MD5Update(&md5, (u_char *)pkt, (u_int)length);
  68. MD5Final(digest, &md5);
  69. if (size != 16 + 4)
  70. return (0);
  71. return (!memcmp(digest, (char *)pkt + length + 4, 16));
  72. }
  73. /*
  74. * Calculate the reference id from the address. If it is an IPv4
  75. * address, use it as is. If it is an IPv6 address, do a md5 on
  76. * it and use the bottom 4 bytes.
  77. */
  78. u_int32
  79. addr2refid(struct sockaddr_storage *addr)
  80. {
  81. MD5_CTX md5;
  82. u_char digest[16];
  83. u_int32 addr_refid;
  84. if (addr->ss_family == AF_INET)
  85. return (GET_INADDR(*addr));
  86. MD5Init(&md5);
  87. MD5Update(&md5, (u_char *)&GET_INADDR6(*addr),
  88. sizeof(struct in6_addr));
  89. MD5Final(digest, &md5);
  90. memcpy(&addr_refid, digest, 4);
  91. return (addr_refid);
  92. }