auth.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. 20080912
  3. D. J. Bernstein
  4. Public domain.
  5. */
  6. #include "crypto_onetimeauth.h"
  7. static void add(unsigned int h[17],const unsigned int c[17])
  8. {
  9. unsigned int j;
  10. unsigned int u;
  11. u = 0;
  12. for (j = 0;j < 17;++j) { u += h[j] + c[j]; h[j] = u & 255; u >>= 8; }
  13. }
  14. static void squeeze(unsigned int h[17])
  15. {
  16. unsigned int j;
  17. unsigned int u;
  18. u = 0;
  19. for (j = 0;j < 16;++j) { u += h[j]; h[j] = u & 255; u >>= 8; }
  20. u += h[16]; h[16] = u & 3;
  21. u = 5 * (u >> 2);
  22. for (j = 0;j < 16;++j) { u += h[j]; h[j] = u & 255; u >>= 8; }
  23. u += h[16]; h[16] = u;
  24. }
  25. static const unsigned int minusp[17] = {
  26. 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252
  27. } ;
  28. static void freeze(unsigned int h[17])
  29. {
  30. unsigned int horig[17];
  31. unsigned int j;
  32. unsigned int negative;
  33. for (j = 0;j < 17;++j) horig[j] = h[j];
  34. add(h,minusp);
  35. negative = -(h[16] >> 7);
  36. for (j = 0;j < 17;++j) h[j] ^= negative & (horig[j] ^ h[j]);
  37. }
  38. static void mulmod(unsigned int h[17],const unsigned int r[17])
  39. {
  40. unsigned int hr[17];
  41. unsigned int i;
  42. unsigned int j;
  43. unsigned int u;
  44. for (i = 0;i < 17;++i) {
  45. u = 0;
  46. for (j = 0;j <= i;++j) u += h[j] * r[i - j];
  47. for (j = i + 1;j < 17;++j) u += 320 * h[j] * r[i + 17 - j];
  48. hr[i] = u;
  49. }
  50. for (i = 0;i < 17;++i) h[i] = hr[i];
  51. squeeze(h);
  52. }
  53. int crypto_onetimeauth(unsigned char *out,const unsigned char *in,unsigned long long inlen,const unsigned char *k)
  54. {
  55. unsigned int j;
  56. unsigned int r[17];
  57. unsigned int h[17];
  58. unsigned int c[17];
  59. r[0] = k[0];
  60. r[1] = k[1];
  61. r[2] = k[2];
  62. r[3] = k[3] & 15;
  63. r[4] = k[4] & 252;
  64. r[5] = k[5];
  65. r[6] = k[6];
  66. r[7] = k[7] & 15;
  67. r[8] = k[8] & 252;
  68. r[9] = k[9];
  69. r[10] = k[10];
  70. r[11] = k[11] & 15;
  71. r[12] = k[12] & 252;
  72. r[13] = k[13];
  73. r[14] = k[14];
  74. r[15] = k[15] & 15;
  75. r[16] = 0;
  76. for (j = 0;j < 17;++j) h[j] = 0;
  77. while (inlen > 0) {
  78. for (j = 0;j < 17;++j) c[j] = 0;
  79. for (j = 0;(j < 16) && (j < inlen);++j) c[j] = in[j];
  80. c[j] = 1;
  81. in += j; inlen -= j;
  82. add(h,c);
  83. mulmod(h,r);
  84. }
  85. freeze(h);
  86. for (j = 0;j < 16;++j) c[j] = k[j + 16];
  87. c[16] = 0;
  88. add(h,c);
  89. for (j = 0;j < 16;++j) out[j] = h[j];
  90. return 0;
  91. }