cram.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* $Id$
  2. *
  3. * isync - IMAP4 to maildir mailbox synchronizer
  4. * Copyright (C) 2000 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. #include <assert.h>
  21. #include "isync.h"
  22. #if HAVE_LIBSSL
  23. #include <openssl/hmac.h>
  24. #define ENCODED_SIZE(n) (4*((n+2)/3))
  25. static char
  26. hexchar (unsigned int b)
  27. {
  28. if (b < 10)
  29. return '0' + b;
  30. return 'a' + (b - 10);
  31. }
  32. char *
  33. cram (const char *challenge, const char *user, const char *pass)
  34. {
  35. HMAC_CTX hmac;
  36. char hash[16];
  37. char hex[33];
  38. int i;
  39. unsigned int hashlen = sizeof (hash);
  40. char buf[256];
  41. int len = strlen (challenge);
  42. char *response = calloc (1, 1 + len);
  43. char *final;
  44. /* response will always be smaller than challenge because we are
  45. * decoding.
  46. */
  47. len = EVP_DecodeBlock ((unsigned char *) response, (unsigned char *) challenge, strlen (challenge));
  48. // printf ("CRAM-MD5 challege is %s\n", response);
  49. HMAC_Init (&hmac, (unsigned char *) pass, strlen (pass), EVP_md5 ());
  50. HMAC_Update (&hmac, (unsigned char *) response, strlen(response));
  51. HMAC_Final (&hmac, (unsigned char *) hash, &hashlen);
  52. assert (hashlen == sizeof (hash));
  53. free (response);
  54. hex[32] = 0;
  55. for (i = 0; i < 16; i++)
  56. {
  57. hex[2 * i] = hexchar ((hash[i] >> 4) & 0xf);
  58. hex[2 * i + 1] = hexchar (hash[i] & 0xf);
  59. }
  60. snprintf (buf, sizeof (buf), "%s %s", user, hex);
  61. // printf ("Response: %s\n", buf);
  62. len = strlen (buf);
  63. len = ENCODED_SIZE (len) + 1;
  64. final = malloc (len);
  65. final[len - 1] = 0;
  66. assert (EVP_EncodeBlock ((unsigned char *) final, (unsigned char *) buf, strlen (buf)) == len - 1);
  67. return final;
  68. }
  69. #endif