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