hmac.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include "os.h"
  10. #include <libsec.h>
  11. /* rfc2104 */
  12. static DigestState*
  13. hmac_x(uint8_t *p, uint32_t len, uint8_t *key, uint32_t klen,
  14. uint8_t *digest,
  15. DigestState *s,
  16. DigestState*(*x)(uint8_t*, uint32_t, uint8_t*, DigestState*),
  17. int xlen)
  18. {
  19. int i;
  20. uint8_t pad[65], innerdigest[256];
  21. if(xlen > sizeof(innerdigest))
  22. return nil;
  23. if(klen>64)
  24. return nil;
  25. /* first time through */
  26. if(s == nil){
  27. for(i=0; i<64; i++)
  28. pad[i] = 0x36;
  29. pad[64] = 0;
  30. for(i=0; i<klen; i++)
  31. pad[i] ^= key[i];
  32. s = (*x)(pad, 64, nil, nil);
  33. if(s == nil)
  34. return nil;
  35. }
  36. s = (*x)(p, len, nil, s);
  37. if(digest == nil)
  38. return s;
  39. /* last time through */
  40. for(i=0; i<64; i++)
  41. pad[i] = 0x5c;
  42. pad[64] = 0;
  43. for(i=0; i<klen; i++)
  44. pad[i] ^= key[i];
  45. (*x)(nil, 0, innerdigest, s);
  46. s = (*x)(pad, 64, nil, nil);
  47. (*x)(innerdigest, xlen, digest, s);
  48. return nil;
  49. }
  50. DigestState*
  51. hmac_sha1(uint8_t *p, uint32_t len, uint8_t *key, uint32_t klen,
  52. uint8_t *digest,
  53. DigestState *s)
  54. {
  55. return hmac_x(p, len, key, klen, digest, s, sha1, SHA1dlen);
  56. }
  57. DigestState*
  58. hmac_md5(uint8_t *p, uint32_t len, uint8_t *key, uint32_t klen,
  59. uint8_t *digest,
  60. DigestState *s)
  61. {
  62. return hmac_x(p, len, key, klen, digest, s, md5, MD5dlen);
  63. }