1
0

hmac.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * 20080913
  3. * D. J. Bernstein
  4. * Public domain.
  5. * */
  6. #include "crypto_hashblocks_sha512.h"
  7. #include "crypto_auth.h"
  8. #define blocks crypto_hashblocks_sha512
  9. typedef unsigned long long uint64;
  10. static const unsigned char iv[64] = {
  11. 0x6a,0x09,0xe6,0x67,0xf3,0xbc,0xc9,0x08,
  12. 0xbb,0x67,0xae,0x85,0x84,0xca,0xa7,0x3b,
  13. 0x3c,0x6e,0xf3,0x72,0xfe,0x94,0xf8,0x2b,
  14. 0xa5,0x4f,0xf5,0x3a,0x5f,0x1d,0x36,0xf1,
  15. 0x51,0x0e,0x52,0x7f,0xad,0xe6,0x82,0xd1,
  16. 0x9b,0x05,0x68,0x8c,0x2b,0x3e,0x6c,0x1f,
  17. 0x1f,0x83,0xd9,0xab,0xfb,0x41,0xbd,0x6b,
  18. 0x5b,0xe0,0xcd,0x19,0x13,0x7e,0x21,0x79
  19. } ;
  20. int crypto_auth(unsigned char *out,const unsigned char *in,unsigned long long inlen,const unsigned char *k)
  21. {
  22. unsigned char h[64];
  23. unsigned char padded[256];
  24. int i;
  25. unsigned long long bytes = 128 + inlen;
  26. for (i = 0;i < 64;++i) h[i] = iv[i];
  27. for (i = 0;i < 32;++i) padded[i] = k[i] ^ 0x36;
  28. for (i = 32;i < 128;++i) padded[i] = 0x36;
  29. blocks(h,padded,128);
  30. blocks(h,in,inlen);
  31. in += inlen;
  32. inlen &= 127;
  33. in -= inlen;
  34. for (i = 0;i < inlen;++i) padded[i] = in[i];
  35. padded[inlen] = 0x80;
  36. if (inlen < 112) {
  37. for (i = inlen + 1;i < 119;++i) padded[i] = 0;
  38. padded[119] = bytes >> 61;
  39. padded[120] = bytes >> 53;
  40. padded[121] = bytes >> 45;
  41. padded[122] = bytes >> 37;
  42. padded[123] = bytes >> 29;
  43. padded[124] = bytes >> 21;
  44. padded[125] = bytes >> 13;
  45. padded[126] = bytes >> 5;
  46. padded[127] = bytes << 3;
  47. blocks(h,padded,128);
  48. } else {
  49. for (i = inlen + 1;i < 247;++i) padded[i] = 0;
  50. padded[247] = bytes >> 61;
  51. padded[248] = bytes >> 53;
  52. padded[249] = bytes >> 45;
  53. padded[250] = bytes >> 37;
  54. padded[251] = bytes >> 29;
  55. padded[252] = bytes >> 21;
  56. padded[253] = bytes >> 13;
  57. padded[254] = bytes >> 5;
  58. padded[255] = bytes << 3;
  59. blocks(h,padded,256);
  60. }
  61. for (i = 0;i < 32;++i) padded[i] = k[i] ^ 0x5c;
  62. for (i = 32;i < 128;++i) padded[i] = 0x5c;
  63. for (i = 0;i < 64;++i) padded[128 + i] = h[i];
  64. for (i = 0;i < 64;++i) h[i] = iv[i];
  65. for (i = 64;i < 128;++i) padded[128 + i] = 0;
  66. padded[128 + 64] = 0x80;
  67. padded[128 + 126] = 6;
  68. blocks(h,padded,256);
  69. for (i = 0;i < 32;++i) out[i] = h[i];
  70. return 0;
  71. }