libsodium: Needed for Dnscrypto-proxy Release 1.3.0
[tomato.git] / release / src / router / libsodium / src / libsodium / crypto_onetimeauth / poly1305 / ref / auth_poly1305_ref.c
blob9c4219eb4162b261173ad64a4ccb8d6886b9823f
1 /*
2 20080912
3 D. J. Bernstein
4 Public domain.
5 */
7 #include "api.h"
8 #include "crypto_onetimeauth_poly1305_ref.h"
9 #include "utils.h"
11 static void add(unsigned int h[17],const unsigned int c[17])
13 unsigned int j;
14 unsigned int u;
15 u = 0;
16 for (j = 0;j < 17;++j) { u += h[j] + c[j]; h[j] = u & 255; u >>= 8; }
19 static void squeeze(unsigned int h[17])
21 unsigned int j;
22 unsigned int u;
23 u = 0;
24 for (j = 0;j < 16;++j) { u += h[j]; h[j] = u & 255; u >>= 8; }
25 u += h[16]; h[16] = u & 3;
26 u = 5 * (u >> 2);
27 for (j = 0;j < 16;++j) { u += h[j]; h[j] = u & 255; u >>= 8; }
28 u += h[16]; h[16] = u;
31 static const unsigned int minusp[17] = {
32 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252
33 } ;
35 static void freeze(unsigned int h[17])
37 unsigned int horig[17];
38 unsigned int j;
39 unsigned int negative;
40 for (j = 0;j < 17;++j) horig[j] = h[j];
41 add(h,minusp);
42 negative = -(h[16] >> 7);
43 for (j = 0;j < 17;++j) h[j] ^= negative & (horig[j] ^ h[j]);
46 static void mulmod(unsigned int h[17],const unsigned int r[17])
48 unsigned int hr[17];
49 unsigned int i;
50 unsigned int j;
51 unsigned int u;
53 for (i = 0;i < 17;++i) {
54 u = 0;
55 for (j = 0;j <= i;++j) u += h[j] * r[i - j];
56 for (j = i + 1;j < 17;++j) u += 320 * h[j] * r[i + 17 - j];
57 hr[i] = u;
59 for (i = 0;i < 17;++i) h[i] = hr[i];
60 squeeze(h);
63 int crypto_onetimeauth(unsigned char *out,const unsigned char *in,unsigned long long inlen,const unsigned char *k)
65 unsigned int j;
66 unsigned int r[17];
67 unsigned int h[17];
68 unsigned int c[17];
70 r[0] = k[0];
71 r[1] = k[1];
72 r[2] = k[2];
73 r[3] = k[3] & 15;
74 r[4] = k[4] & 252;
75 r[5] = k[5];
76 r[6] = k[6];
77 r[7] = k[7] & 15;
78 r[8] = k[8] & 252;
79 r[9] = k[9];
80 r[10] = k[10];
81 r[11] = k[11] & 15;
82 r[12] = k[12] & 252;
83 r[13] = k[13];
84 r[14] = k[14];
85 r[15] = k[15] & 15;
86 r[16] = 0;
88 for (j = 0;j < 17;++j) h[j] = 0;
90 while (inlen > 0) {
91 for (j = 0;j < 17;++j) c[j] = 0;
92 for (j = 0;(j < 16) && (j < inlen);++j) c[j] = in[j];
93 c[j] = 1;
94 in += j; inlen -= j;
95 add(h,c);
96 mulmod(h,r);
99 freeze(h);
101 for (j = 0;j < 16;++j) c[j] = k[j + 16];
102 c[16] = 0;
103 add(h,c);
104 for (j = 0;j < 16;++j) out[j] = h[j];
105 return 0;
108 const char *
109 crypto_onetimeauth_poly1305_implementation_name(void)
111 return "ref";
114 struct crypto_onetimeauth_poly1305_implementation
115 crypto_onetimeauth_poly1305_ref_implementation = {
116 _SODIUM_C99(.implementation_name =) crypto_onetimeauth_poly1305_implementation_name,
117 _SODIUM_C99(.onetimeauth =) crypto_onetimeauth,
118 _SODIUM_C99(.onetimeauth_verify =) crypto_onetimeauth_verify