hmac_sha1.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* $OpenBSD: hmac_sha1.c,v 1.1 2012/10/09 12:36:50 jsing Exp $ */
  2. /*-
  3. * Copyright (c) 2008 Damien Bergamini <damien.bergamini@free.fr>
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include <sys/param.h>
  18. #include <lib/libsa/stand.h>
  19. #include "hmac_sha1.h"
  20. /*
  21. * HMAC-SHA-1 (from RFC 2202).
  22. */
  23. void
  24. hmac_sha1(const u_int8_t *text, size_t text_len, const u_int8_t *key,
  25. size_t key_len, u_int8_t digest[SHA1_DIGEST_LENGTH])
  26. {
  27. SHA1_CTX ctx;
  28. u_int8_t k_pad[SHA1_BLOCK_LENGTH];
  29. u_int8_t tk[SHA1_DIGEST_LENGTH];
  30. int i;
  31. if (key_len > SHA1_BLOCK_LENGTH) {
  32. SHA1Init(&ctx);
  33. SHA1Update(&ctx, key, key_len);
  34. SHA1Final(tk, &ctx);
  35. key = tk;
  36. key_len = SHA1_DIGEST_LENGTH;
  37. }
  38. bzero(k_pad, sizeof k_pad);
  39. bcopy(key, k_pad, key_len);
  40. for (i = 0; i < SHA1_BLOCK_LENGTH; i++)
  41. k_pad[i] ^= 0x36;
  42. SHA1Init(&ctx);
  43. SHA1Update(&ctx, k_pad, SHA1_BLOCK_LENGTH);
  44. SHA1Update(&ctx, text, text_len);
  45. SHA1Final(digest, &ctx);
  46. bzero(k_pad, sizeof k_pad);
  47. bcopy(key, k_pad, key_len);
  48. for (i = 0; i < SHA1_BLOCK_LENGTH; i++)
  49. k_pad[i] ^= 0x5c;
  50. SHA1Init(&ctx);
  51. SHA1Update(&ctx, k_pad, SHA1_BLOCK_LENGTH);
  52. SHA1Update(&ctx, digest, SHA1_DIGEST_LENGTH);
  53. SHA1Final(digest, &ctx);
  54. }