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