cram.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* $Id$
  2. *
  3. * isync - IMAP4 to maildir mailbox synchronizer
  4. * Copyright (C) 2000-2 Michael R. Elkins <me@mutt.org>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. *
  20. * As a special exception, isync may be linked with the OpenSSL library,
  21. * despite that library's more restrictive license.
  22. */
  23. #include <assert.h>
  24. #include "isync.h"
  25. #if HAVE_LIBSSL
  26. #include <string.h>
  27. #include <openssl/hmac.h>
  28. #define ENCODED_SIZE(n) (4*((n+2)/3))
  29. static char
  30. hexchar (unsigned int b)
  31. {
  32. if (b < 10)
  33. return '0' + b;
  34. return 'a' + (b - 10);
  35. }
  36. char *
  37. cram (const char *challenge, const char *user, const char *pass)
  38. {
  39. HMAC_CTX hmac;
  40. char hash[16];
  41. char hex[33];
  42. int i;
  43. unsigned int hashlen = sizeof (hash);
  44. char buf[256];
  45. int len = strlen (challenge);
  46. char *response = calloc (1, 1 + len);
  47. char *final;
  48. /* response will always be smaller than challenge because we are
  49. * decoding.
  50. */
  51. len = EVP_DecodeBlock ((unsigned char *) response, (unsigned char *) challenge, strlen (challenge));
  52. HMAC_Init (&hmac, (unsigned char *) pass, strlen (pass), EVP_md5 ());
  53. HMAC_Update (&hmac, (unsigned char *) response, strlen(response));
  54. HMAC_Final (&hmac, (unsigned char *) hash, &hashlen);
  55. assert (hashlen == sizeof (hash));
  56. free (response);
  57. hex[32] = 0;
  58. for (i = 0; i < 16; i++)
  59. {
  60. hex[2 * i] = hexchar ((hash[i] >> 4) & 0xf);
  61. hex[2 * i + 1] = hexchar (hash[i] & 0xf);
  62. }
  63. snprintf (buf, sizeof (buf), "%s %s", user, hex);
  64. len = strlen (buf);
  65. len = ENCODED_SIZE (len) + 1;
  66. final = malloc (len);
  67. final[len - 1] = 0;
  68. assert (EVP_EncodeBlock ((unsigned char *) final, (unsigned char *) buf, strlen (buf)) == len - 1);
  69. return final;
  70. }
  71. #endif