cram.c 2.3 KB

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