ecp_nistz256 update.
[openssl.git] / crypto / ec / ecp_nistz256.c
1 /******************************************************************************
2  *                                                                            *
3  * Copyright 2014 Intel Corporation                                           *
4  *                                                                            *
5  * Licensed under the Apache License, Version 2.0 (the "License");            *
6  * you may not use this file except in compliance with the License.           *
7  * You may obtain a copy of the License at                                    *
8  *                                                                            *
9  *    http://www.apache.org/licenses/LICENSE-2.0                              *
10  *                                                                            *
11  * Unless required by applicable law or agreed to in writing, software        *
12  * distributed under the License is distributed on an "AS IS" BASIS,          *
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
14  * See the License for the specific language governing permissions and        *
15  * limitations under the License.                                             *
16  *                                                                            *
17  ******************************************************************************
18  *                                                                            *
19  * Developers and authors:                                                    *
20  * Shay Gueron (1, 2), and Vlad Krasnov (1)                                   *
21  * (1) Intel Corporation, Israel Development Center                           *
22  * (2) University of Haifa                                                    *
23  * Reference:                                                                 *
24  * S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with *
25  *                          256 Bit Primes"                                   *
26  *                                                                            *
27  ******************************************************************************/
28
29 #include <string.h>
30
31 #include <openssl/bn.h>
32 #include <openssl/err.h>
33 #include <openssl/ec.h>
34 #include "cryptlib.h"
35
36 #include "ec_lcl.h"
37
38 #if BN_BITS2 != 64
39 # define TOBN(hi,lo)    lo,hi
40 #else
41 # define TOBN(hi,lo)    ((BN_ULONG)hi<<32|lo)
42 #endif
43
44 #if defined(__GNUC__)
45 # define ALIGN32        __attribute((aligned(32)))
46 #elif defined(_MSC_VER)
47 # define ALIGN32        __declspec(align(32))
48 #else
49 # define ALIGN32
50 #endif
51
52 #define ALIGNPTR(p,N)   ((unsigned char *)p+N-(size_t)p%N)
53 #define P256_LIMBS      (256/BN_BITS2)
54
55 typedef unsigned short u16;
56
57 typedef struct {
58     BN_ULONG X[P256_LIMBS];
59     BN_ULONG Y[P256_LIMBS];
60     BN_ULONG Z[P256_LIMBS];
61 } P256_POINT;
62
63 typedef struct {
64     BN_ULONG X[P256_LIMBS];
65     BN_ULONG Y[P256_LIMBS];
66 } P256_POINT_AFFINE;
67
68 typedef P256_POINT_AFFINE PRECOMP256_ROW[64];
69
70 /* structure for precomputed multiples of the generator */
71 typedef struct ec_pre_comp_st {
72     const EC_GROUP *group;      /* Parent EC_GROUP object */
73     size_t w;                   /* Window size */
74     /* Constant time access to the X and Y coordinates of the pre-computed,
75      * generator multiplies, in the Montgomery domain. Pre-calculated
76      * multiplies are stored in affine form. */
77     PRECOMP256_ROW *precomp;
78     void *precomp_storage;
79     int references;
80 } EC_PRE_COMP;
81
82 /* Functions implemented in assembly */
83 /* Modular mul by 2: res = 2*a mod P */
84 void ecp_nistz256_mul_by_2(BN_ULONG res[P256_LIMBS],
85                            const BN_ULONG a[P256_LIMBS]);
86 /* Modular div by 2: res = a/2 mod P */
87 void ecp_nistz256_div_by_2(BN_ULONG res[P256_LIMBS],
88                            const BN_ULONG a[P256_LIMBS]);
89 /* Modular mul by 3: res = 3*a mod P */
90 void ecp_nistz256_mul_by_3(BN_ULONG res[P256_LIMBS],
91                            const BN_ULONG a[P256_LIMBS]);
92 /* Modular add: res = a+b mod P   */
93 void ecp_nistz256_add(BN_ULONG res[P256_LIMBS],
94                       const BN_ULONG a[P256_LIMBS],
95                       const BN_ULONG b[P256_LIMBS]);
96 /* Modular sub: res = a-b mod P   */
97 void ecp_nistz256_sub(BN_ULONG res[P256_LIMBS],
98                       const BN_ULONG a[P256_LIMBS],
99                       const BN_ULONG b[P256_LIMBS]);
100 /* Modular neg: res = -a mod P    */
101 void ecp_nistz256_neg(BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS]);
102 /* Montgomery mul: res = a*b*2^-256 mod P */
103 void ecp_nistz256_mul_mont(BN_ULONG res[P256_LIMBS],
104                            const BN_ULONG a[P256_LIMBS],
105                            const BN_ULONG b[P256_LIMBS]);
106 /* Montgomery sqr: res = a*a*2^-256 mod P */
107 void ecp_nistz256_sqr_mont(BN_ULONG res[P256_LIMBS],
108                            const BN_ULONG a[P256_LIMBS]);
109 /* Convert a number from Montgomery domain, by multiplying with 1 */
110 void ecp_nistz256_from_mont(BN_ULONG res[P256_LIMBS],
111                             const BN_ULONG in[P256_LIMBS]);
112 /* Convert a number to Montgomery domain, by multiplying with 2^512 mod P*/
113 void ecp_nistz256_to_mont(BN_ULONG res[P256_LIMBS],
114                           const BN_ULONG in[P256_LIMBS]);
115 /* Functions that perform constant time access to the precomputed tables */
116 void ecp_nistz256_scatter_w5(P256_POINT * val,
117                             const P256_POINT * in_t, int index);
118 void ecp_nistz256_gather_w5(P256_POINT * val,
119                             const P256_POINT * in_t, int index);
120 void ecp_nistz256_scatter_w7(P256_POINT_AFFINE * val,
121                             const P256_POINT_AFFINE * in_t, int index);
122 void ecp_nistz256_gather_w7(P256_POINT_AFFINE * val,
123                             const P256_POINT_AFFINE * in_t, int index);
124
125 /* One converted into the Montgomery domain */
126 static const BN_ULONG ONE[P256_LIMBS] = {
127     TOBN(0x00000000, 0x00000001), TOBN(0xffffffff, 0x00000000),
128     TOBN(0xffffffff, 0xffffffff), TOBN(0x00000000, 0xfffffffe)
129 };
130
131 static void *ecp_nistz256_pre_comp_dup(void *);
132 static void ecp_nistz256_pre_comp_free(void *);
133 static void ecp_nistz256_pre_comp_clear_free(void *);
134 static EC_PRE_COMP *ecp_nistz256_pre_comp_new(const EC_GROUP * group);
135
136 /* Precomputed tables for the default generator */
137 extern const PRECOMP256_ROW ecp_nistz256_precomputed[37];
138
139 /* Recode window to a signed digit, see ecp_nistputil.c for details */
140 static unsigned int _booth_recode_w5(unsigned int in)
141 {
142     unsigned int s, d;
143
144     s = ~((in >> 5) - 1);
145     d = (1 << 6) - in - 1;
146     d = (d & s) | (in & ~s);
147     d = (d >> 1) + (d & 1);
148
149     return (d << 1) + (s & 1);
150 }
151
152 static unsigned int _booth_recode_w7(unsigned int in)
153 {
154     unsigned int s, d;
155
156     s = ~((in >> 7) - 1);
157     d = (1 << 8) - in - 1;
158     d = (d & s) | (in & ~s);
159     d = (d >> 1) + (d & 1);
160
161     return (d << 1) + (s & 1);
162 }
163
164 static void copy_conditional(BN_ULONG dst[P256_LIMBS],
165                              const BN_ULONG src[P256_LIMBS], BN_ULONG move)
166 {
167     BN_ULONG mask1 = -move;
168     BN_ULONG mask2 = ~mask1;
169
170     dst[0] = (src[0] & mask1) ^ (dst[0] & mask2);
171     dst[1] = (src[1] & mask1) ^ (dst[1] & mask2);
172     dst[2] = (src[2] & mask1) ^ (dst[2] & mask2);
173     dst[3] = (src[3] & mask1) ^ (dst[3] & mask2);
174     if (P256_LIMBS == 8) {
175         dst[4] = (src[4] & mask1) ^ (dst[4] & mask2);
176         dst[5] = (src[5] & mask1) ^ (dst[5] & mask2);
177         dst[6] = (src[6] & mask1) ^ (dst[6] & mask2);
178         dst[7] = (src[7] & mask1) ^ (dst[7] & mask2);
179     }
180 }
181
182 static BN_ULONG is_zero(BN_ULONG in)
183 {
184     in |= (0 - in);
185     in = ~in;
186     in &= BN_MASK2;
187     in >>= BN_BITS2 - 1;
188     return in;
189 }
190
191 static BN_ULONG is_equal(const BN_ULONG a[P256_LIMBS],
192                          const BN_ULONG b[P256_LIMBS])
193 {
194     BN_ULONG res;
195
196     res = a[0] ^ b[0];
197     res |= a[1] ^ b[1];
198     res |= a[2] ^ b[2];
199     res |= a[3] ^ b[3];
200     if (P256_LIMBS == 8) {
201         res |= a[4] ^ b[4];
202         res |= a[5] ^ b[5];
203         res |= a[6] ^ b[6];
204         res |= a[7] ^ b[7];
205     }
206
207     return is_zero(res);
208 }
209
210 static BN_ULONG is_one(const BN_ULONG a[P256_LIMBS])
211 {
212     BN_ULONG res;
213
214     res = a[0] ^ ONE[0];
215     res |= a[1] ^ ONE[1];
216     res |= a[2] ^ ONE[2];
217     res |= a[3] ^ ONE[3];
218     if (P256_LIMBS == 8) {
219         res |= a[4] ^ ONE[4];
220         res |= a[5] ^ ONE[5];
221         res |= a[6] ^ ONE[6];
222     }
223
224     return is_zero(res);
225 }
226
227 #ifndef ECP_NISTZ256_REFERENCE_IMPLEMENTATION
228 void ecp_nistz256_point_double(P256_POINT * r, const P256_POINT * a);
229 void ecp_nistz256_point_add(P256_POINT * r,
230                             const P256_POINT * a, const P256_POINT * b);
231 void ecp_nistz256_point_add_affine(P256_POINT * r,
232                                    const P256_POINT * a,
233                                    const P256_POINT_AFFINE * b);
234 #else
235 /* Point double: r = 2*a */
236 static void ecp_nistz256_point_double(P256_POINT * r, const P256_POINT * a)
237 {
238     BN_ULONG S[P256_LIMBS];
239     BN_ULONG M[P256_LIMBS];
240     BN_ULONG Zsqr[P256_LIMBS];
241     BN_ULONG tmp0[P256_LIMBS];
242
243     const BN_ULONG *in_x = a->X;
244     const BN_ULONG *in_y = a->Y;
245     const BN_ULONG *in_z = a->Z;
246
247     BN_ULONG *res_x = r->X;
248     BN_ULONG *res_y = r->Y;
249     BN_ULONG *res_z = r->Z;
250
251     ecp_nistz256_mul_by_2(S, in_y);
252
253     ecp_nistz256_sqr_mont(Zsqr, in_z);
254
255     ecp_nistz256_sqr_mont(S, S);
256
257     ecp_nistz256_mul_mont(res_z, in_z, in_y);
258     ecp_nistz256_mul_by_2(res_z, res_z);
259
260     ecp_nistz256_add(M, in_x, Zsqr);
261     ecp_nistz256_sub(Zsqr, in_x, Zsqr);
262
263     ecp_nistz256_sqr_mont(res_y, S);
264     ecp_nistz256_div_by_2(res_y, res_y);
265
266     ecp_nistz256_mul_mont(M, M, Zsqr);
267     ecp_nistz256_mul_by_3(M, M);
268
269     ecp_nistz256_mul_mont(S, S, in_x);
270     ecp_nistz256_mul_by_2(tmp0, S);
271
272     ecp_nistz256_sqr_mont(res_x, M);
273
274     ecp_nistz256_sub(res_x, res_x, tmp0);
275     ecp_nistz256_sub(S, S, res_x);
276
277     ecp_nistz256_mul_mont(S, S, M);
278     ecp_nistz256_sub(res_y, S, res_y);
279 }
280
281 /* Point addition: r = a+b */
282 static void ecp_nistz256_point_add(P256_POINT * r,
283                                    const P256_POINT * a, const P256_POINT * b)
284 {
285     BN_ULONG U2[P256_LIMBS], S2[P256_LIMBS];
286     BN_ULONG U1[P256_LIMBS], S1[P256_LIMBS];
287     BN_ULONG Z1sqr[P256_LIMBS];
288     BN_ULONG Z2sqr[P256_LIMBS];
289     BN_ULONG H[P256_LIMBS], R[P256_LIMBS];
290     BN_ULONG Hsqr[P256_LIMBS];
291     BN_ULONG Rsqr[P256_LIMBS];
292     BN_ULONG Hcub[P256_LIMBS];
293
294     BN_ULONG res_x[P256_LIMBS];
295     BN_ULONG res_y[P256_LIMBS];
296     BN_ULONG res_z[P256_LIMBS];
297
298     BN_ULONG in1infty, in2infty;
299
300     const BN_ULONG *in1_x = a->X;
301     const BN_ULONG *in1_y = a->Y;
302     const BN_ULONG *in1_z = a->Z;
303
304     const BN_ULONG *in2_x = b->X;
305     const BN_ULONG *in2_y = b->Y;
306     const BN_ULONG *in2_z = b->Z;
307
308     /* We encode infinity as (0,0), which is not on the curve,
309      * so it is OK. */
310     in1infty = in1_x[0] | in1_x[1] | in1_x[2] | in1_x[3] |
311                in1_y[0] | in1_y[1] | in1_y[2] | in1_y[3];
312     if (P256_LIMBS == 8)
313         in1infty |= in1_x[4] | in1_x[5] | in1_x[6] | in1_x[7] |
314                     in1_y[4] | in1_y[5] | in1_y[6] | in1_y[7];
315
316     in2infty = in2_x[0] | in2_x[1] | in2_x[2] | in2_x[3] |
317                in2_y[0] | in2_y[1] | in2_y[2] | in2_y[3];
318     if (P256_LIMBS == 8)
319         in2infty |= in2_x[4] | in2_x[5] | in2_x[6] | in2_x[7] |
320                     in2_y[4] | in2_y[5] | in2_y[6] | in2_y[7];
321
322     in1infty = is_zero(in1infty);
323     in2infty = is_zero(in2infty);
324
325     ecp_nistz256_sqr_mont(Z2sqr, in2_z);        /* Z2^2 */
326     ecp_nistz256_sqr_mont(Z1sqr, in1_z);        /* Z1^2 */
327
328     ecp_nistz256_mul_mont(S1, Z2sqr, in2_z);    /* S1 = Z2^3 */
329     ecp_nistz256_mul_mont(S2, Z1sqr, in1_z);    /* S2 = Z1^3 */
330
331     ecp_nistz256_mul_mont(S1, S1, in1_y);       /* S1 = Y1*Z2^3 */
332     ecp_nistz256_mul_mont(S2, S2, in2_y);       /* S2 = Y2*Z1^3 */
333     ecp_nistz256_sub(R, S2, S1);                /* R = S2 - S1 */
334
335     ecp_nistz256_mul_mont(U1, in1_x, Z2sqr);    /* U1 = X1*Z2^2 */
336     ecp_nistz256_mul_mont(U2, in2_x, Z1sqr);    /* U2 = X2*Z1^2 */
337     ecp_nistz256_sub(H, U2, U1);                /* H = U2 - U1 */
338
339     /* This should not happen during sign/ecdh,
340      * so no constant time violation */
341     if (is_equal(U1, U2) && !in1infty && !in2infty) {
342         if (is_equal(S1, S2)) {
343             ecp_nistz256_point_double(r, a);
344             return;
345         } else {
346             memset(r, 0, sizeof(*r));
347             return;
348         }
349     }
350
351     ecp_nistz256_sqr_mont(Rsqr, R);             /* R^2 */
352     ecp_nistz256_mul_mont(res_z, H, in1_z);     /* Z3 = H*Z1*Z2 */
353     ecp_nistz256_sqr_mont(Hsqr, H);             /* H^2 */
354     ecp_nistz256_mul_mont(res_z, res_z, in2_z); /* Z3 = H*Z1*Z2 */
355     ecp_nistz256_mul_mont(Hcub, Hsqr, H);       /* H^3 */
356
357     ecp_nistz256_mul_mont(U2, U1, Hsqr);        /* U1*H^2 */
358     ecp_nistz256_mul_by_2(Hsqr, U2);            /* 2*U1*H^2 */
359
360     ecp_nistz256_sub(res_x, Rsqr, Hsqr);
361     ecp_nistz256_sub(res_x, res_x, Hcub);
362
363     ecp_nistz256_sub(res_y, U2, res_x);
364
365     ecp_nistz256_mul_mont(S2, S1, Hcub);
366     ecp_nistz256_mul_mont(res_y, R, res_y);
367     ecp_nistz256_sub(res_y, res_y, S2);
368
369     copy_conditional(res_x, in2_x, in1infty);
370     copy_conditional(res_y, in2_y, in1infty);
371     copy_conditional(res_z, in2_z, in1infty);
372
373     copy_conditional(res_x, in1_x, in2infty);
374     copy_conditional(res_y, in1_y, in2infty);
375     copy_conditional(res_z, in1_z, in2infty);
376
377     memcpy(r->X, res_x, sizeof(res_x));
378     memcpy(r->Y, res_y, sizeof(res_y));
379     memcpy(r->Z, res_z, sizeof(res_z));
380 }
381
382 /* Point addition when b is known to be affine: r = a+b */
383 static void ecp_nistz256_point_add_affine(P256_POINT * r,
384                                           const P256_POINT * a,
385                                           const P256_POINT_AFFINE * b)
386 {
387     BN_ULONG U2[P256_LIMBS], S2[P256_LIMBS];
388     BN_ULONG Z1sqr[P256_LIMBS];
389     BN_ULONG H[P256_LIMBS], R[P256_LIMBS];
390     BN_ULONG Hsqr[P256_LIMBS];
391     BN_ULONG Rsqr[P256_LIMBS];
392     BN_ULONG Hcub[P256_LIMBS];
393
394     BN_ULONG res_x[P256_LIMBS];
395     BN_ULONG res_y[P256_LIMBS];
396     BN_ULONG res_z[P256_LIMBS];
397
398     BN_ULONG in1infty, in2infty;
399
400     const BN_ULONG *in1_x = a->X;
401     const BN_ULONG *in1_y = a->Y;
402     const BN_ULONG *in1_z = a->Z;
403
404     const BN_ULONG *in2_x = b->X;
405     const BN_ULONG *in2_y = b->Y;
406
407     /* In affine representation we encode infty as (0,0),
408      * which is not on the curve, so it is OK */
409     in1infty = in1_x[0] | in1_x[1] | in1_x[2] | in1_x[3] |
410                in1_y[0] | in1_y[1] | in1_y[2] | in1_y[3];
411     if (P256_LIMBS == 8)
412         in1infty |= in1_x[4] | in1_x[5] | in1_x[6] | in1_x[7] |
413                     in1_y[4] | in1_y[5] | in1_y[6] | in1_y[7];
414
415     in2infty = in2_x[0] | in2_x[1] | in2_x[2] | in2_x[3] |
416                in2_y[0] | in2_y[1] | in2_y[2] | in2_y[3];
417     if (P256_LIMBS == 8)
418         in2infty |= in2_x[4] | in2_x[5] | in2_x[6] | in2_x[7] |
419                     in2_y[4] | in2_y[5] | in2_y[6] | in2_y[7];
420
421     in1infty = is_zero(in1infty);
422     in2infty = is_zero(in2infty);
423
424     ecp_nistz256_sqr_mont(Z1sqr, in1_z);        /* Z1^2 */
425
426     ecp_nistz256_mul_mont(U2, in2_x, Z1sqr);    /* U2 = X2*Z1^2 */
427     ecp_nistz256_sub(H, U2, in1_x);             /* H = U2 - U1 */
428
429     ecp_nistz256_mul_mont(S2, Z1sqr, in1_z);    /* S2 = Z1^3 */
430
431     ecp_nistz256_mul_mont(res_z, H, in1_z);     /* Z3 = H*Z1*Z2 */
432
433     ecp_nistz256_mul_mont(S2, S2, in2_y);       /* S2 = Y2*Z1^3 */
434     ecp_nistz256_sub(R, S2, in1_y);             /* R = S2 - S1 */
435
436     ecp_nistz256_sqr_mont(Hsqr, H);             /* H^2 */
437     ecp_nistz256_sqr_mont(Rsqr, R);             /* R^2 */
438     ecp_nistz256_mul_mont(Hcub, Hsqr, H);       /* H^3 */
439
440     ecp_nistz256_mul_mont(U2, in1_x, Hsqr);     /* U1*H^2 */
441     ecp_nistz256_mul_by_2(Hsqr, U2);            /* 2*U1*H^2 */
442
443     ecp_nistz256_sub(res_x, Rsqr, Hsqr);
444     ecp_nistz256_sub(res_x, res_x, Hcub);
445     ecp_nistz256_sub(H, U2, res_x);
446
447     ecp_nistz256_mul_mont(S2, in1_y, Hcub);
448     ecp_nistz256_mul_mont(H, H, R);
449     ecp_nistz256_sub(res_y, H, S2);
450
451     copy_conditional(res_x, in2_x, in1infty);
452     copy_conditional(res_x, in1_x, in2infty);
453
454     copy_conditional(res_y, in2_y, in1infty);
455     copy_conditional(res_y, in1_y, in2infty);
456
457     copy_conditional(res_z, ONE, in1infty);
458     copy_conditional(res_z, in1_z, in2infty);
459
460     memcpy(r->X, res_x, sizeof(res_x));
461     memcpy(r->Y, res_y, sizeof(res_y));
462     memcpy(r->Z, res_z, sizeof(res_z));
463 }
464 #endif
465
466 /* r = in^-1 mod p */
467 static void ecp_nistz256_mod_inverse(BN_ULONG r[P256_LIMBS],
468                                      const BN_ULONG in[P256_LIMBS])
469 {
470     /* The poly is ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff
471        We use FLT and used poly-2 as exponent */
472     BN_ULONG p2[P256_LIMBS];
473     BN_ULONG p4[P256_LIMBS];
474     BN_ULONG p8[P256_LIMBS];
475     BN_ULONG p16[P256_LIMBS];
476     BN_ULONG p32[P256_LIMBS];
477     BN_ULONG res[P256_LIMBS];
478     int i;
479
480     ecp_nistz256_sqr_mont(res, in);
481     ecp_nistz256_mul_mont(p2, res, in);         /* 3*p */
482
483     ecp_nistz256_sqr_mont(res, p2);
484     ecp_nistz256_sqr_mont(res, res);
485     ecp_nistz256_mul_mont(p4, res, p2);         /* f*p */
486
487     ecp_nistz256_sqr_mont(res, p4);
488     ecp_nistz256_sqr_mont(res, res);
489     ecp_nistz256_sqr_mont(res, res);
490     ecp_nistz256_sqr_mont(res, res);
491     ecp_nistz256_mul_mont(p8, res, p4);         /* ff*p */
492
493     ecp_nistz256_sqr_mont(res, p8);
494     for (i = 0; i < 7; i++)
495         ecp_nistz256_sqr_mont(res, res);
496     ecp_nistz256_mul_mont(p16, res, p8);        /* ffff*p */
497
498     ecp_nistz256_sqr_mont(res, p16);
499     for (i = 0; i < 15; i++)
500         ecp_nistz256_sqr_mont(res, res);
501     ecp_nistz256_mul_mont(p32, res, p16);       /* ffffffff*p */
502
503     ecp_nistz256_sqr_mont(res, p32);
504     for (i = 0; i < 31; i++)
505         ecp_nistz256_sqr_mont(res, res);
506     ecp_nistz256_mul_mont(res, res, in);
507
508     for (i = 0; i < 32 * 4; i++)
509         ecp_nistz256_sqr_mont(res, res);
510     ecp_nistz256_mul_mont(res, res, p32);
511
512     for (i = 0; i < 32; i++)
513         ecp_nistz256_sqr_mont(res, res);
514     ecp_nistz256_mul_mont(res, res, p32);
515
516     for (i = 0; i < 16; i++)
517         ecp_nistz256_sqr_mont(res, res);
518     ecp_nistz256_mul_mont(res, res, p16);
519
520     for (i = 0; i < 8; i++)
521         ecp_nistz256_sqr_mont(res, res);
522     ecp_nistz256_mul_mont(res, res, p8);
523
524     ecp_nistz256_sqr_mont(res, res);
525     ecp_nistz256_sqr_mont(res, res);
526     ecp_nistz256_sqr_mont(res, res);
527     ecp_nistz256_sqr_mont(res, res);
528     ecp_nistz256_mul_mont(res, res, p4);
529
530     ecp_nistz256_sqr_mont(res, res);
531     ecp_nistz256_sqr_mont(res, res);
532     ecp_nistz256_mul_mont(res, res, p2);
533
534     ecp_nistz256_sqr_mont(res, res);
535     ecp_nistz256_sqr_mont(res, res);
536     ecp_nistz256_mul_mont(res, res, in);
537
538     memcpy(r, res, sizeof(res));
539 }
540
541 /* ecp_nistz256_bignum_to_field_elem copies the contents of |in| to |out| and
542  * returns one if it fits. Otherwise it returns zero. */
543 static int ecp_nistz256_bignum_to_field_elem(BN_ULONG out[P256_LIMBS],
544                                              const BIGNUM * in)
545 {
546     if (in->top > P256_LIMBS)
547         return 0;
548
549     memset(out, 0, sizeof(BN_ULONG) * P256_LIMBS);
550     memcpy(out, in->d, sizeof(BN_ULONG) * in->top);
551     return 1;
552 }
553
554 /* r = sum(scalar[i]*point[i]) */
555 static void ecp_nistz256_windowed_mul(const EC_GROUP * group,
556                                       P256_POINT * r,
557                                       const BIGNUM ** scalar,
558                                       const EC_POINT ** point,
559                                       int num, BN_CTX * ctx)
560 {
561     int i, j;
562     unsigned int index;
563     unsigned char (*p_str)[33] = NULL;
564     const unsigned int window_size = 5;
565     const unsigned int mask = (1 << (window_size + 1)) - 1;
566     unsigned int wvalue;
567     P256_POINT *temp;   /* place for 5 temporary points */
568     const BIGNUM **scalars = NULL;
569     P256_POINT(*table)[16] = NULL;
570     void *table_storage = NULL;
571
572     if ((table_storage =
573          OPENSSL_malloc((num * 16 + 5) * sizeof(P256_POINT) + 64)) == NULL
574         || (p_str =
575             OPENSSL_malloc(num * 33 * sizeof(unsigned char))) == NULL
576         || (scalars = OPENSSL_malloc(num * sizeof(BIGNUM *))) == NULL) {
577         ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, ERR_R_MALLOC_FAILURE);
578         goto err;
579     }
580
581     table = (void *)ALIGNPTR(table_storage, 64);
582     temp  = (P256_POINT *)(table + num);
583
584     for (i = 0; i < num; i++) {
585         P256_POINT *row = table[i];
586
587         if ((BN_num_bits(scalar[i]) > 256) || BN_is_negative(scalar[i])) {
588             BIGNUM *mod;
589
590             if ((mod = BN_CTX_get(ctx)) == NULL)
591                 goto err;
592             if (!BN_nnmod(mod, scalar[i], &group->order, ctx)) {
593                 ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, ERR_R_BN_LIB);
594                 goto err;
595             }
596             scalars[i] = mod;
597         } else
598             scalars[i] = scalar[i];
599
600         for (j = 0; j < scalars[i]->top * BN_BYTES; j += BN_BYTES) {
601             BN_ULONG d = scalars[i]->d[j / BN_BYTES];
602
603             p_str[i][j + 0] = d & 0xff;
604             p_str[i][j + 1] = (d >> 8) & 0xff;
605             p_str[i][j + 2] = (d >> 16) & 0xff;
606             p_str[i][j + 3] = (d >>= 24) & 0xff;
607             if (BN_BYTES == 8) {
608                 d >>= 8;
609                 p_str[i][j + 4] = d & 0xff;
610                 p_str[i][j + 5] = (d >> 8) & 0xff;
611                 p_str[i][j + 6] = (d >> 16) & 0xff;
612                 p_str[i][j + 7] = (d >> 24) & 0xff;
613             }
614         }
615         for (; j < 33; j++)
616             p_str[i][j] = 0;
617
618         if (!ecp_nistz256_bignum_to_field_elem(temp[0].X, &point[i]->X)
619             || !ecp_nistz256_bignum_to_field_elem(temp[0].Y, &point[i]->Y)
620             || !ecp_nistz256_bignum_to_field_elem(temp[0].Z, &point[i]->Z)) {
621             ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, EC_R_COORDINATES_OUT_OF_RANGE);
622             goto err;
623         }
624
625         /* row[0] is implicitly (0,0,0) (the point at infinity),
626          * therefore it is not stored. All other values are actually
627          * stored with an offset of -1 in table.
628          */
629
630         ecp_nistz256_scatter_w5  (row, &temp[0], 1);
631         ecp_nistz256_point_double(&temp[1], &temp[0]);              /*1+1=2  */
632         ecp_nistz256_scatter_w5  (row, &temp[1], 2);
633         ecp_nistz256_point_add   (&temp[2], &temp[1], &temp[0]);    /*2+1=3  */
634         ecp_nistz256_scatter_w5  (row, &temp[2], 3);
635         ecp_nistz256_point_double(&temp[1], &temp[1]);              /*2*2=4  */
636         ecp_nistz256_scatter_w5  (row, &temp[1], 4);
637         ecp_nistz256_point_double(&temp[2], &temp[2]);              /*2*3=6  */
638         ecp_nistz256_scatter_w5  (row, &temp[2], 6);
639         ecp_nistz256_point_add   (&temp[3], &temp[1], &temp[0]);    /*4+1=5  */
640         ecp_nistz256_scatter_w5  (row, &temp[3], 5);
641         ecp_nistz256_point_add   (&temp[4], &temp[2], &temp[0]);    /*6+1=7  */
642         ecp_nistz256_scatter_w5  (row, &temp[4], 7);
643         ecp_nistz256_point_double(&temp[1], &temp[1]);              /*2*4=8  */
644         ecp_nistz256_scatter_w5  (row, &temp[1], 8);
645         ecp_nistz256_point_double(&temp[2], &temp[2]);              /*2*6=12 */
646         ecp_nistz256_scatter_w5  (row, &temp[2], 12);
647         ecp_nistz256_point_double(&temp[3], &temp[3]);              /*2*5=10 */
648         ecp_nistz256_scatter_w5  (row, &temp[3], 10);
649         ecp_nistz256_point_double(&temp[4], &temp[4]);              /*2*7=14 */
650         ecp_nistz256_scatter_w5  (row, &temp[4], 14);
651         ecp_nistz256_point_add   (&temp[2], &temp[2], &temp[0]);    /*12+1=13*/
652         ecp_nistz256_scatter_w5  (row, &temp[2], 13);
653         ecp_nistz256_point_add   (&temp[3], &temp[3], &temp[0]);    /*10+1=11*/
654         ecp_nistz256_scatter_w5  (row, &temp[3], 11);
655         ecp_nistz256_point_add   (&temp[4], &temp[4], &temp[0]);    /*14+1=15*/
656         ecp_nistz256_scatter_w5  (row, &temp[4], 15);
657         ecp_nistz256_point_add   (&temp[2], &temp[1], &temp[0]);    /*8+1=9  */
658         ecp_nistz256_scatter_w5  (row, &temp[2], 9);
659         ecp_nistz256_point_double(&temp[1], &temp[1]);              /*2*8=16 */
660         ecp_nistz256_scatter_w5  (row, &temp[1], 16);
661     }
662
663     index = 255;
664
665     wvalue = p_str[0][(index - 1) / 8];
666     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
667
668     /*
669      * We gather to temp[0], because we know it's position relative
670      * to table
671      */
672     ecp_nistz256_gather_w5(&temp[0], table[0], _booth_recode_w5(wvalue) >> 1);
673     memcpy(r, &temp[0], sizeof(temp[0]));
674
675     while (index >= 5) {
676         for (i = (index == 255 ? 1 : 0); i < num; i++) {
677             unsigned int off = (index - 1) / 8;
678
679             wvalue = p_str[i][off] | p_str[i][off + 1] << 8;
680             wvalue = (wvalue >> ((index - 1) % 8)) & mask;
681
682             wvalue = _booth_recode_w5(wvalue);
683
684             ecp_nistz256_gather_w5(&temp[0], table[i], wvalue >> 1);
685
686             ecp_nistz256_neg(temp[1].Y, temp[0].Y);
687             copy_conditional(temp[0].Y, temp[1].Y, (wvalue & 1));
688
689             ecp_nistz256_point_add(r, r, &temp[0]);
690         }
691
692         index -= window_size;
693
694         ecp_nistz256_point_double(r, r);
695         ecp_nistz256_point_double(r, r);
696         ecp_nistz256_point_double(r, r);
697         ecp_nistz256_point_double(r, r);
698         ecp_nistz256_point_double(r, r);
699     }
700
701     /* Final window */
702     for (i = 0; i < num; i++) {
703         wvalue = p_str[i][0];
704         wvalue = (wvalue << 1) & mask;
705
706         wvalue = _booth_recode_w5(wvalue);
707
708         ecp_nistz256_gather_w5(&temp[0], table[i], wvalue >> 1);
709
710         ecp_nistz256_neg(temp[1].Y, temp[0].Y);
711         copy_conditional(temp[0].Y, temp[1].Y, wvalue & 1);
712
713         ecp_nistz256_point_add(r, r, &temp[0]);
714     }
715
716 err:
717     if (table_storage)
718         OPENSSL_free(table_storage);
719     if (p_str)
720         OPENSSL_free(p_str);
721     if (scalars)
722         OPENSSL_free(scalars);
723 }
724
725 /* Coordinates of G, for which we have precomputed tables */
726 const static BN_ULONG def_xG[P256_LIMBS] = {
727     TOBN(0x79e730d4, 0x18a9143c), TOBN(0x75ba95fc, 0x5fedb601),
728     TOBN(0x79fb732b, 0x77622510), TOBN(0x18905f76, 0xa53755c6)
729 };
730
731 const static BN_ULONG def_yG[P256_LIMBS] = {
732     TOBN(0xddf25357, 0xce95560a), TOBN(0x8b4ab8e4, 0xba19e45c),
733     TOBN(0xd2e88688, 0xdd21f325), TOBN(0x8571ff18, 0x25885d85)
734 };
735
736 /* ecp_nistz256_is_affine_G returns one if |generator| is the standard,
737  * P-256 generator. */
738 static int ecp_nistz256_is_affine_G(const EC_POINT * generator)
739 {
740     return (generator->X.top == P256_LIMBS) &&
741         (generator->Y.top == P256_LIMBS) &&
742         (generator->Z.top == (P256_LIMBS - P256_LIMBS / 8)) &&
743         is_equal(generator->X.d, def_xG) &&
744         is_equal(generator->Y.d, def_yG) && is_one(generator->Z.d);
745 }
746
747 static int ecp_nistz256_mult_precompute(EC_GROUP * group, BN_CTX * ctx)
748 {
749     /* We precompute a table for a Booth encoded exponent (wNAF) based
750      * computation. Each table holds 64 values for safe access, with an
751      * implicit value of infinity at index zero. We use window of size 7,
752      * and therefore require ceil(256/7) = 37 tables. */
753     BIGNUM *order;
754     EC_POINT *P = NULL, *T = NULL;
755     const EC_POINT *generator;
756     EC_PRE_COMP *pre_comp;
757     int i, j, k, ret = 0;
758     size_t w;
759
760     PRECOMP256_ROW *preComputedTable = NULL;
761     unsigned char *precomp_storage = NULL;
762
763     /* if there is an old EC_PRE_COMP object, throw it away */
764     EC_EX_DATA_free_data(&group->extra_data, ecp_nistz256_pre_comp_dup,
765                          ecp_nistz256_pre_comp_free,
766                          ecp_nistz256_pre_comp_clear_free);
767
768     generator = EC_GROUP_get0_generator(group);
769     if (generator == NULL) {
770         ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, EC_R_UNDEFINED_GENERATOR);
771         return 0;
772     }
773
774     if (ecp_nistz256_is_affine_G(generator)) {
775         /* No need to calculate tables for the standard generator
776          * because we have them statically. */
777         return 1;
778     }
779
780     if ((pre_comp = ecp_nistz256_pre_comp_new(group)) == NULL)
781         return 0;
782
783     if (ctx == NULL) {
784         ctx = BN_CTX_new();
785         if (ctx == NULL)
786             goto err;
787     }
788
789     BN_CTX_start(ctx);
790     order = BN_CTX_get(ctx);
791
792     if (order == NULL)
793         goto err;
794
795     if (!EC_GROUP_get_order(group, order, ctx))
796         goto err;
797
798     if (BN_is_zero(order)) {
799         ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, EC_R_UNKNOWN_ORDER);
800         goto err;
801     }
802
803     w = 7;
804
805     if ((precomp_storage =
806          OPENSSL_malloc(37 * 64 * sizeof(P256_POINT_AFFINE) + 64)) == NULL) {
807         ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, ERR_R_MALLOC_FAILURE);
808         goto err;
809     }
810
811     preComputedTable = (void *)ALIGNPTR(precomp_storage, 64);
812
813     P = EC_POINT_new(group);
814     T = EC_POINT_new(group);
815
816     /* The zero entry is implicitly infinity, and we skip it,
817      * storing other values with -1 offset. */
818     EC_POINT_copy(T, generator);
819
820     for (k = 0; k < 64; k++) {
821         EC_POINT_copy(P, T);
822         for (j = 0; j < 37; j++) {
823             P256_POINT_AFFINE temp;
824             /* It would be faster to use
825              * ec_GFp_simple_points_make_affine and make multiple
826              * points affine at the same time. */
827             ec_GFp_simple_make_affine(group, P, ctx);
828             ecp_nistz256_bignum_to_field_elem(temp.X, &P->X);
829             ecp_nistz256_bignum_to_field_elem(temp.Y, &P->Y);
830             ecp_nistz256_scatter_w7(preComputedTable[j], &temp, k);
831             for (i = 0; i < 7; i++)
832                 ec_GFp_simple_dbl(group, P, P, ctx);
833         }
834         ec_GFp_simple_add(group, T, T, generator, ctx);
835     }
836
837     pre_comp->group = group;
838     pre_comp->w = w;
839     pre_comp->precomp = preComputedTable;
840     pre_comp->precomp_storage = precomp_storage;
841
842     precomp_storage = NULL;
843
844     if (!EC_EX_DATA_set_data(&group->extra_data, pre_comp,
845                              ecp_nistz256_pre_comp_dup,
846                              ecp_nistz256_pre_comp_free,
847                              ecp_nistz256_pre_comp_clear_free)) {
848         goto err;
849     }
850
851     pre_comp = NULL;
852
853     ret = 1;
854
855 err:
856     if (ctx != NULL)
857         BN_CTX_end(ctx);
858     if (pre_comp)
859         ecp_nistz256_pre_comp_free(pre_comp);
860     if (precomp_storage)
861         OPENSSL_free(precomp_storage);
862     if (P)
863         EC_POINT_free(P);
864     if (T)
865         EC_POINT_free(T);
866     return ret;
867 }
868
869 /*
870  * Note that by default ECP_NISTZ256_AVX2 is undefined. While it's great
871  * code processing 4 points in parallel, corresponding serial operation
872  * is several times slower, because it uses 29x29=58-bit multiplication
873  * as opposite to 64x64=128-bit in integer-only scalar case. As result
874  * it doesn't provide *significant* performance improvement. Note that
875  * just defining ECP_NISTZ256_AVX2 is not sufficient to make it work,
876  * you'd need to compile even asm/ecp_nistz256-avx.pl module.
877  */
878 #if defined(ECP_NISTZ256_AVX2)
879 # if !(defined(__x86_64) || defined(__x86_64__) || \
880        defined(_M_AMD64) || defined(_MX64)) || \
881      !(defined(__GNUC__) || defined(_MSC_VER)) /* this is for ALIGN32 */
882 #  undef ECP_NISTZ256_AVX2
883 # else
884 /* Constant time access, loading four values, from four consecutive tables */
885 void ecp_nistz256_avx2_multi_gather_w7(void *result, const void *in, int index0,
886                                        int index1, int index2, int index3);
887 void ecp_nistz256_avx2_transpose_convert(void *RESULTx4, const void *in);
888 void ecp_nistz256_avx2_convert_transpose_back(void *result, const void *Ax4);
889 void ecp_nistz256_avx2_point_add_affine_x4(void *RESULTx4, const void *Ax4,
890                                            const void *Bx4);
891 void ecp_nistz256_avx2_point_add_affines_x4(void *RESULTx4, const void *Ax4,
892                                             const void *Bx4);
893 void ecp_nistz256_avx2_to_mont(void *RESULTx4, const void *Ax4);
894 void ecp_nistz256_avx2_from_mont(void *RESULTx4, const void *Ax4);
895 void ecp_nistz256_avx2_set1(void *RESULTx4);
896 int ecp_nistz_avx2_eligible(void);
897
898 static void booth_recode_w7(unsigned char *sign,
899                             unsigned char *digit, unsigned char in)
900 {
901     unsigned char s, d;
902
903     s = ~((in >> 7) - 1);
904     d = (1 << 8) - in - 1;
905     d = (d & s) | (in & ~s);
906     d = (d >> 1) + (d & 1);
907
908     *sign = s & 1;
909     *digit = d;
910 }
911
912 /* ecp_nistz256_avx2_mul_g performs multiplication by G, using only the
913  * precomputed table. It does 4 affine point additions in parallel,
914  * significantly speeding up point multiplication for a fixed value. */
915 static void ecp_nistz256_avx2_mul_g(P256_POINT * r,
916                                     unsigned char p_str[33],
917                                     const
918                                     P256_POINT_AFFINE(*preComputedTable)[64])
919 {
920     const unsigned int window_size = 7;
921     const unsigned int mask = (1 << (window_size + 1)) - 1;
922     unsigned int wvalue;
923     /* Using 4 windows at a time */
924     unsigned char sign0, digit0;
925     unsigned char sign1, digit1;
926     unsigned char sign2, digit2;
927     unsigned char sign3, digit3;
928     unsigned int index = 0;
929     BN_ULONG tmp[P256_LIMBS];
930     int i;
931
932     ALIGN32 BN_ULONG aX4[4 * 9 * 3] = { 0 };
933     ALIGN32 BN_ULONG bX4[4 * 9 * 2] = { 0 };
934     ALIGN32 P256_POINT_AFFINE point_arr[4];
935     ALIGN32 P256_POINT res_point_arr[4];
936
937     /* Initial four windows */
938     wvalue = *((u16 *) & p_str[0]);
939     wvalue = (wvalue << 1) & mask;
940     index += window_size;
941     booth_recode_w7(&sign0, &digit0, wvalue);
942     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
943     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
944     index += window_size;
945     booth_recode_w7(&sign1, &digit1, wvalue);
946     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
947     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
948     index += window_size;
949     booth_recode_w7(&sign2, &digit2, wvalue);
950     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
951     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
952     index += window_size;
953     booth_recode_w7(&sign3, &digit3, wvalue);
954
955     ecp_nistz256_avx2_multi_gather_w7(point_arr, preComputedTable[0],
956                                       digit0, digit1, digit2, digit3);
957
958     ecp_nistz256_neg(tmp, point_arr[0].Y);
959     copy_conditional(point_arr[0].Y, tmp, sign0);
960     ecp_nistz256_neg(tmp, point_arr[1].Y);
961     copy_conditional(point_arr[1].Y, tmp, sign1);
962     ecp_nistz256_neg(tmp, point_arr[2].Y);
963     copy_conditional(point_arr[2].Y, tmp, sign2);
964     ecp_nistz256_neg(tmp, point_arr[3].Y);
965     copy_conditional(point_arr[3].Y, tmp, sign3);
966
967     ecp_nistz256_avx2_transpose_convert(aX4, point_arr);
968     ecp_nistz256_avx2_to_mont(aX4, aX4);
969     ecp_nistz256_avx2_to_mont(&aX4[4 * 9], &aX4[4 * 9]);
970     ecp_nistz256_avx2_set1(&aX4[4 * 9 * 2]);
971
972     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
973     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
974     index += window_size;
975     booth_recode_w7(&sign0, &digit0, wvalue);
976     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
977     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
978     index += window_size;
979     booth_recode_w7(&sign1, &digit1, wvalue);
980     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
981     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
982     index += window_size;
983     booth_recode_w7(&sign2, &digit2, wvalue);
984     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
985     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
986     index += window_size;
987     booth_recode_w7(&sign3, &digit3, wvalue);
988
989     ecp_nistz256_avx2_multi_gather_w7(point_arr, preComputedTable[4 * 1],
990                                       digit0, digit1, digit2, digit3);
991
992     ecp_nistz256_neg(tmp, point_arr[0].Y);
993     copy_conditional(point_arr[0].Y, tmp, sign0);
994     ecp_nistz256_neg(tmp, point_arr[1].Y);
995     copy_conditional(point_arr[1].Y, tmp, sign1);
996     ecp_nistz256_neg(tmp, point_arr[2].Y);
997     copy_conditional(point_arr[2].Y, tmp, sign2);
998     ecp_nistz256_neg(tmp, point_arr[3].Y);
999     copy_conditional(point_arr[3].Y, tmp, sign3);
1000
1001     ecp_nistz256_avx2_transpose_convert(bX4, point_arr);
1002     ecp_nistz256_avx2_to_mont(bX4, bX4);
1003     ecp_nistz256_avx2_to_mont(&bX4[4 * 9], &bX4[4 * 9]);
1004     /* Optimized when both inputs are affine */
1005     ecp_nistz256_avx2_point_add_affines_x4(aX4, aX4, bX4);
1006
1007     for (i = 2; i < 9; i++) {
1008         wvalue = *((u16 *) & p_str[(index - 1) / 8]);
1009         wvalue = (wvalue >> ((index - 1) % 8)) & mask;
1010         index += window_size;
1011         booth_recode_w7(&sign0, &digit0, wvalue);
1012         wvalue = *((u16 *) & p_str[(index - 1) / 8]);
1013         wvalue = (wvalue >> ((index - 1) % 8)) & mask;
1014         index += window_size;
1015         booth_recode_w7(&sign1, &digit1, wvalue);
1016         wvalue = *((u16 *) & p_str[(index - 1) / 8]);
1017         wvalue = (wvalue >> ((index - 1) % 8)) & mask;
1018         index += window_size;
1019         booth_recode_w7(&sign2, &digit2, wvalue);
1020         wvalue = *((u16 *) & p_str[(index - 1) / 8]);
1021         wvalue = (wvalue >> ((index - 1) % 8)) & mask;
1022         index += window_size;
1023         booth_recode_w7(&sign3, &digit3, wvalue);
1024
1025         ecp_nistz256_avx2_multi_gather_w7(point_arr,
1026                                           preComputedTable[4 * i],
1027                                           digit0, digit1, digit2, digit3);
1028
1029         ecp_nistz256_neg(tmp, point_arr[0].Y);
1030         copy_conditional(point_arr[0].Y, tmp, sign0);
1031         ecp_nistz256_neg(tmp, point_arr[1].Y);
1032         copy_conditional(point_arr[1].Y, tmp, sign1);
1033         ecp_nistz256_neg(tmp, point_arr[2].Y);
1034         copy_conditional(point_arr[2].Y, tmp, sign2);
1035         ecp_nistz256_neg(tmp, point_arr[3].Y);
1036         copy_conditional(point_arr[3].Y, tmp, sign3);
1037
1038         ecp_nistz256_avx2_transpose_convert(bX4, point_arr);
1039         ecp_nistz256_avx2_to_mont(bX4, bX4);
1040         ecp_nistz256_avx2_to_mont(&bX4[4 * 9], &bX4[4 * 9]);
1041
1042         ecp_nistz256_avx2_point_add_affine_x4(aX4, aX4, bX4);
1043     }
1044
1045     ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 0], &aX4[4 * 9 * 0]);
1046     ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 1], &aX4[4 * 9 * 1]);
1047     ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 2], &aX4[4 * 9 * 2]);
1048
1049     ecp_nistz256_avx2_convert_transpose_back(res_point_arr, aX4);
1050     /* Last window is performed serially */
1051     wvalue = *((u16 *) & p_str[(index - 1) / 8]);
1052     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
1053     booth_recode_w7(&sign0, &digit0, wvalue);
1054     ecp_nistz256_gather_w7((P256_POINT_AFFINE *) r,
1055                                 preComputedTable[36], digit0);
1056     ecp_nistz256_neg(tmp, r->Y);
1057     copy_conditional(r->Y, tmp, sign0);
1058     memcpy(r->Z, ONE, sizeof(ONE));
1059     /* Sum the four windows */
1060     ecp_nistz256_point_add(r, r, &res_point_arr[0]);
1061     ecp_nistz256_point_add(r, r, &res_point_arr[1]);
1062     ecp_nistz256_point_add(r, r, &res_point_arr[2]);
1063     ecp_nistz256_point_add(r, r, &res_point_arr[3]);
1064 }
1065 # endif
1066 #endif
1067
1068 static int ecp_nistz256_set_from_affine(EC_POINT * out, const EC_GROUP * group,
1069                                         const P256_POINT_AFFINE * in,
1070                                         BN_CTX * ctx)
1071 {
1072     BIGNUM x, y;
1073     BN_ULONG d_x[P256_LIMBS], d_y[P256_LIMBS];
1074     int ret = 0;
1075
1076     memcpy(d_x, in->X, sizeof(d_x));
1077     x.d = d_x;
1078     x.dmax = x.top = P256_LIMBS;
1079     x.neg = 0;
1080     x.flags = BN_FLG_STATIC_DATA;
1081
1082     memcpy(d_y, in->Y, sizeof(d_y));
1083     y.d = d_y;
1084     y.dmax = y.top = P256_LIMBS;
1085     y.neg = 0;
1086     y.flags = BN_FLG_STATIC_DATA;
1087
1088     ret = EC_POINT_set_affine_coordinates_GFp(group, out, &x, &y, ctx);
1089
1090     return ret;
1091 }
1092
1093 /* r = scalar*G + sum(scalars[i]*points[i]) */
1094 static int ecp_nistz256_points_mul(const EC_GROUP * group,
1095                                    EC_POINT * r,
1096                                    const BIGNUM * scalar,
1097                                    size_t num,
1098                                    const EC_POINT * points[],
1099                                    const BIGNUM * scalars[], BN_CTX * ctx)
1100 {
1101     int i = 0, ret = 0, no_precomp_for_generator = 0, p_is_infinity = 0;
1102     size_t j;
1103     unsigned char p_str[33] = { 0 };
1104     const PRECOMP256_ROW *preComputedTable = NULL;
1105     const EC_PRE_COMP *pre_comp = NULL;
1106     const EC_POINT *generator = NULL;
1107     unsigned int index = 0;
1108     const unsigned int window_size = 7;
1109     const unsigned int mask = (1 << (window_size + 1)) - 1;
1110     unsigned int wvalue;
1111     ALIGN32 union {
1112         P256_POINT p;
1113         P256_POINT_AFFINE a;
1114     } t, p;
1115     BIGNUM *tmp_scalar;
1116
1117     if ((num+1) == 0 || (num+1) > OPENSSL_MALLOC_MAX_NELEMS(void *)) {
1118         ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
1119         return 0;
1120     }
1121
1122     if (group->meth != r->meth) {
1123         ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
1124         return 0;
1125     }
1126     if ((scalar == NULL) && (num == 0))
1127         return EC_POINT_set_to_infinity(group, r);
1128
1129     for (j = 0; j < num; j++) {
1130         if (group->meth != points[j]->meth) {
1131             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
1132             return 0;
1133         }
1134     }
1135
1136     /* Need 256 bits for space for all coordinates. */
1137     bn_wexpand(&r->X, P256_LIMBS);
1138     bn_wexpand(&r->Y, P256_LIMBS);
1139     bn_wexpand(&r->Z, P256_LIMBS);
1140     r->X.top = P256_LIMBS;
1141     r->Y.top = P256_LIMBS;
1142     r->Z.top = P256_LIMBS;
1143
1144     if (scalar) {
1145         generator = EC_GROUP_get0_generator(group);
1146         if (generator == NULL) {
1147             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_UNDEFINED_GENERATOR);
1148             goto err;
1149         }
1150
1151         /* look if we can use precomputed multiples of generator */
1152         pre_comp =
1153             EC_EX_DATA_get_data(group->extra_data, ecp_nistz256_pre_comp_dup,
1154                                 ecp_nistz256_pre_comp_free,
1155                                 ecp_nistz256_pre_comp_clear_free);
1156
1157         if (pre_comp) {
1158             /* If there is a precomputed table for the generator,
1159              * check that it was generated with the same
1160              * generator. */
1161             EC_POINT *pre_comp_generator = EC_POINT_new(group);
1162             if (pre_comp_generator == NULL)
1163                 goto err;
1164
1165             if (!ecp_nistz256_set_from_affine(pre_comp_generator,
1166                                               group, pre_comp->precomp[0],
1167                                               ctx))
1168                 goto err;
1169
1170             if (0 == EC_POINT_cmp(group, generator, pre_comp_generator, ctx))
1171                 preComputedTable = (const PRECOMP256_ROW *)pre_comp->precomp;
1172
1173             EC_POINT_free(pre_comp_generator);
1174         }
1175
1176         if (preComputedTable == NULL && ecp_nistz256_is_affine_G(generator)) {
1177             /* If there is no precomputed data, but the generator
1178              * is the default, a hardcoded table of precomputed
1179              * data is used. This is because applications, such as
1180              * Apache, do not use EC_KEY_precompute_mult. */
1181             preComputedTable = ecp_nistz256_precomputed;
1182         }
1183
1184         if (preComputedTable) {
1185             if ((BN_num_bits(scalar) > 256)
1186                 || BN_is_negative(scalar)) {
1187                 if ((tmp_scalar = BN_CTX_get(ctx)) == NULL)
1188                     goto err;
1189
1190                 if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) {
1191                     ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_BN_LIB);
1192                     goto err;
1193                 }
1194                 scalar = tmp_scalar;
1195             }
1196
1197             for (i = 0; i < scalar->top * BN_BYTES; i += BN_BYTES) {
1198                 BN_ULONG d = scalar->d[i / BN_BYTES];
1199
1200                 p_str[i + 0] = d & 0xff;
1201                 p_str[i + 1] = (d >> 8) & 0xff;
1202                 p_str[i + 2] = (d >> 16) & 0xff;
1203                 p_str[i + 3] = (d >>= 24) & 0xff;
1204                 if (BN_BYTES == 8) {
1205                     d >>= 8;
1206                     p_str[i + 4] = d & 0xff;
1207                     p_str[i + 5] = (d >> 8) & 0xff;
1208                     p_str[i + 6] = (d >> 16) & 0xff;
1209                     p_str[i + 7] = (d >> 24) & 0xff;
1210                 }
1211             }
1212
1213             for (; i < 33; i++)
1214                 p_str[i] = 0;
1215
1216 #if defined(ECP_NISTZ256_AVX2)
1217             if (ecp_nistz_avx2_eligible()) {
1218                 ecp_nistz256_avx2_mul_g(&p.p, p_str, preComputedTable);
1219             } else
1220 #endif
1221             {
1222                 /* First window */
1223                 wvalue = (p_str[0] << 1) & mask;
1224                 index += window_size;
1225
1226                 wvalue = _booth_recode_w7(wvalue);
1227
1228                 ecp_nistz256_gather_w7(&p.a, preComputedTable[0], wvalue >> 1);
1229
1230                 ecp_nistz256_neg(p.p.Z, p.p.Y);
1231                 copy_conditional(p.p.Y, p.p.Z, wvalue & 1);
1232
1233                 memcpy(p.p.Z, ONE, sizeof(ONE));
1234
1235                 for (i = 1; i < 37; i++) {
1236                     unsigned int off = (index - 1) / 8;
1237                     wvalue = p_str[off] | p_str[off + 1] << 8;
1238                     wvalue = (wvalue >> ((index - 1) % 8)) & mask;
1239                     index += window_size;
1240
1241                     wvalue = _booth_recode_w7(wvalue);
1242
1243                     ecp_nistz256_gather_w7(&t.a,
1244                                            preComputedTable[i], wvalue >> 1);
1245
1246                     ecp_nistz256_neg(t.p.Z, t.a.Y);
1247                     copy_conditional(t.a.Y, t.p.Z, wvalue & 1);
1248
1249                     ecp_nistz256_point_add_affine(&p.p, &p.p, &t.a);
1250                 }
1251             }
1252         } else {
1253             p_is_infinity = 1;
1254             no_precomp_for_generator = 1;
1255         }
1256     } else
1257         p_is_infinity = 1;
1258
1259     if (no_precomp_for_generator) {
1260         /* Without a precomputed table for the generator, it has to be
1261          * handled like a normal point. */
1262         const BIGNUM **new_scalars;
1263         const EC_POINT **new_points;
1264
1265         new_scalars = OPENSSL_malloc((num + 1) * sizeof(BIGNUM *));
1266         if (!new_scalars) {
1267             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
1268             return 0;
1269         }
1270
1271         new_points = OPENSSL_malloc((num + 1) * sizeof(EC_POINT *));
1272         if (!new_points) {
1273             OPENSSL_free(new_scalars);
1274             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
1275             return 0;
1276         }
1277
1278         memcpy(new_scalars, scalars, num * sizeof(BIGNUM *));
1279         new_scalars[num] = scalar;
1280         memcpy(new_points, points, num * sizeof(EC_POINT *));
1281         new_points[num] = generator;
1282
1283         scalars = new_scalars;
1284         points = new_points;
1285         num++;
1286     }
1287
1288     if (num) {
1289         P256_POINT *out = &t.p;
1290         if (p_is_infinity)
1291             out = &p.p;
1292
1293         ecp_nistz256_windowed_mul(group, out, scalars, points, num, ctx);
1294
1295         if (!p_is_infinity)
1296             ecp_nistz256_point_add(&p.p, &p.p, out);
1297     }
1298
1299     if (no_precomp_for_generator) {
1300         OPENSSL_free(points);
1301         OPENSSL_free(scalars);
1302     }
1303
1304     memcpy(r->X.d, p.p.X, sizeof(p.p.X));
1305     memcpy(r->Y.d, p.p.Y, sizeof(p.p.Y));
1306     memcpy(r->Z.d, p.p.Z, sizeof(p.p.Z));
1307     bn_correct_top(&r->X);
1308     bn_correct_top(&r->Y);
1309     bn_correct_top(&r->Z);
1310
1311     ret = 1;
1312
1313 err:
1314     return ret;
1315 }
1316
1317 static int ecp_nistz256_get_affine(const EC_GROUP * group,
1318                                    const EC_POINT * point,
1319                                    BIGNUM * x, BIGNUM * y, BN_CTX * ctx)
1320 {
1321     BN_ULONG z_inv2[P256_LIMBS];
1322     BN_ULONG z_inv3[P256_LIMBS];
1323     BN_ULONG x_aff[P256_LIMBS];
1324     BN_ULONG y_aff[P256_LIMBS];
1325     BN_ULONG point_x[P256_LIMBS], point_y[P256_LIMBS], point_z[P256_LIMBS];
1326
1327     if (EC_POINT_is_at_infinity(group, point)) {
1328         ECerr(EC_F_ECP_NISTZ256_GET_AFFINE, EC_R_POINT_AT_INFINITY);
1329         return 0;
1330     }
1331
1332     if (!ecp_nistz256_bignum_to_field_elem(point_x, &point->X) ||
1333         !ecp_nistz256_bignum_to_field_elem(point_y, &point->Y) ||
1334         !ecp_nistz256_bignum_to_field_elem(point_z, &point->Z)) {
1335         ECerr(EC_F_ECP_NISTZ256_GET_AFFINE, EC_R_COORDINATES_OUT_OF_RANGE);
1336         return 0;
1337     }
1338
1339     ecp_nistz256_mod_inverse(z_inv3, point_z);
1340     ecp_nistz256_sqr_mont(z_inv2, z_inv3);
1341     ecp_nistz256_mul_mont(x_aff, z_inv2, point_x);
1342
1343     if (x != NULL) {
1344         bn_wexpand(x, P256_LIMBS);
1345         x->top = P256_LIMBS;
1346         ecp_nistz256_from_mont(x->d, x_aff);
1347         bn_correct_top(x);
1348     }
1349
1350     if (y != NULL) {
1351         ecp_nistz256_mul_mont(z_inv3, z_inv3, z_inv2);
1352         ecp_nistz256_mul_mont(y_aff, z_inv3, point_y);
1353         bn_wexpand(y, P256_LIMBS);
1354         y->top = P256_LIMBS;
1355         ecp_nistz256_from_mont(y->d, y_aff);
1356         bn_correct_top(y);
1357     }
1358
1359     return 1;
1360 }
1361
1362 static EC_PRE_COMP *ecp_nistz256_pre_comp_new(const EC_GROUP * group)
1363 {
1364     EC_PRE_COMP *ret = NULL;
1365
1366     if (!group)
1367         return NULL;
1368
1369     ret = (EC_PRE_COMP *) OPENSSL_malloc(sizeof(EC_PRE_COMP));
1370
1371     if (!ret) {
1372         ECerr(EC_F_ECP_NISTZ256_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
1373         return ret;
1374     }
1375
1376     ret->group = group;
1377     ret->w = 6;                 /* default */
1378     ret->precomp = NULL;
1379     ret->precomp_storage = NULL;
1380     ret->references = 1;
1381     return ret;
1382 }
1383
1384 static void *ecp_nistz256_pre_comp_dup(void *src_)
1385 {
1386     EC_PRE_COMP *src = src_;
1387
1388     /* no need to actually copy, these objects never change! */
1389     CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP);
1390
1391     return src_;
1392 }
1393
1394 static void ecp_nistz256_pre_comp_free(void *pre_)
1395 {
1396     int i;
1397     EC_PRE_COMP *pre = pre_;
1398
1399     if (!pre)
1400         return;
1401
1402     i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
1403     if (i > 0)
1404         return;
1405
1406     if (pre->precomp_storage)
1407         OPENSSL_free(pre->precomp_storage);
1408
1409     OPENSSL_free(pre);
1410 }
1411
1412 static void ecp_nistz256_pre_comp_clear_free(void *pre_)
1413 {
1414     int i;
1415     EC_PRE_COMP *pre = pre_;
1416
1417     if (!pre)
1418         return;
1419
1420     i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
1421     if (i > 0)
1422         return;
1423
1424     if (pre->precomp_storage) {
1425         OPENSSL_cleanse(pre->precomp,
1426                         32 * sizeof(unsigned char) * (1 << pre->w) * 2 * 37);
1427         OPENSSL_free(pre->precomp_storage);
1428     }
1429     OPENSSL_cleanse(pre, sizeof *pre);
1430     OPENSSL_free(pre);
1431 }
1432
1433 static int ecp_nistz256_window_have_precompute_mult(const EC_GROUP * group)
1434 {
1435     /* There is a hard-coded table for the default generator. */
1436     const EC_POINT *generator = EC_GROUP_get0_generator(group);
1437     if (generator != NULL && ecp_nistz256_is_affine_G(generator)) {
1438         /* There is a hard-coded table for the default generator. */
1439         return 1;
1440     }
1441
1442     return EC_EX_DATA_get_data(group->extra_data, ecp_nistz256_pre_comp_dup,
1443                                ecp_nistz256_pre_comp_free,
1444                                ecp_nistz256_pre_comp_clear_free) != NULL;
1445 }
1446
1447 const EC_METHOD *EC_GFp_nistz256_method(void)
1448 {
1449     static const EC_METHOD ret = {
1450         EC_FLAGS_DEFAULT_OCT,
1451         NID_X9_62_prime_field,
1452         ec_GFp_mont_group_init,
1453         ec_GFp_mont_group_finish,
1454         ec_GFp_mont_group_clear_finish,
1455         ec_GFp_mont_group_copy,
1456         ec_GFp_mont_group_set_curve,
1457         ec_GFp_simple_group_get_curve,
1458         ec_GFp_simple_group_get_degree,
1459         ec_GFp_simple_group_check_discriminant,
1460         ec_GFp_simple_point_init,
1461         ec_GFp_simple_point_finish,
1462         ec_GFp_simple_point_clear_finish,
1463         ec_GFp_simple_point_copy,
1464         ec_GFp_simple_point_set_to_infinity,
1465         ec_GFp_simple_set_Jprojective_coordinates_GFp,
1466         ec_GFp_simple_get_Jprojective_coordinates_GFp,
1467         ec_GFp_simple_point_set_affine_coordinates,
1468         ecp_nistz256_get_affine,
1469         0, 0, 0,
1470         ec_GFp_simple_add,
1471         ec_GFp_simple_dbl,
1472         ec_GFp_simple_invert,
1473         ec_GFp_simple_is_at_infinity,
1474         ec_GFp_simple_is_on_curve,
1475         ec_GFp_simple_cmp,
1476         ec_GFp_simple_make_affine,
1477         ec_GFp_simple_points_make_affine,
1478         ecp_nistz256_points_mul,                    /* mul */
1479         ecp_nistz256_mult_precompute,               /* precompute_mult */
1480         ecp_nistz256_window_have_precompute_mult,   /* have_precompute_mult */
1481         ec_GFp_mont_field_mul,
1482         ec_GFp_mont_field_sqr,
1483         0,                                          /* field_div */
1484         ec_GFp_mont_field_encode,
1485         ec_GFp_mont_field_decode,
1486         ec_GFp_mont_field_set_to_one
1487     };
1488
1489     return &ret;
1490 }