801726f9f5560815c9da0e5eca5f7a4186f26c44
[openssl.git] / crypto / ec / ec_mult.c
1 /*
2  * Copyright 2001-2017 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the OpenSSL license (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include <string.h>
12 #include <openssl/err.h>
13
14 #include "internal/cryptlib.h"
15 #include "internal/bn_int.h"
16 #include "ec_lcl.h"
17 #include "internal/refcount.h"
18
19 /*
20  * This file implements the wNAF-based interleaving multi-exponentiation method
21  * Formerly at:
22  *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp
23  * You might now find it here:
24  *   http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13
25  *   http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf
26  * For multiplication with precomputation, we use wNAF splitting, formerly at:
27  *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#fastexp
28  */
29
30 /* structure for precomputed multiples of the generator */
31 struct ec_pre_comp_st {
32     const EC_GROUP *group;      /* parent EC_GROUP object */
33     size_t blocksize;           /* block size for wNAF splitting */
34     size_t numblocks;           /* max. number of blocks for which we have
35                                  * precomputation */
36     size_t w;                   /* window size */
37     EC_POINT **points;          /* array with pre-calculated multiples of
38                                  * generator: 'num' pointers to EC_POINT
39                                  * objects followed by a NULL */
40     size_t num;                 /* numblocks * 2^(w-1) */
41     CRYPTO_REF_COUNT references;
42     CRYPTO_RWLOCK *lock;
43 };
44
45 static EC_PRE_COMP *ec_pre_comp_new(const EC_GROUP *group)
46 {
47     EC_PRE_COMP *ret = NULL;
48
49     if (!group)
50         return NULL;
51
52     ret = OPENSSL_zalloc(sizeof(*ret));
53     if (ret == NULL) {
54         ECerr(EC_F_EC_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
55         return ret;
56     }
57
58     ret->group = group;
59     ret->blocksize = 8;         /* default */
60     ret->w = 4;                 /* default */
61     ret->references = 1;
62
63     ret->lock = CRYPTO_THREAD_lock_new();
64     if (ret->lock == NULL) {
65         ECerr(EC_F_EC_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
66         OPENSSL_free(ret);
67         return NULL;
68     }
69     return ret;
70 }
71
72 EC_PRE_COMP *EC_ec_pre_comp_dup(EC_PRE_COMP *pre)
73 {
74     int i;
75     if (pre != NULL)
76         CRYPTO_UP_REF(&pre->references, &i, pre->lock);
77     return pre;
78 }
79
80 void EC_ec_pre_comp_free(EC_PRE_COMP *pre)
81 {
82     int i;
83
84     if (pre == NULL)
85         return;
86
87     CRYPTO_DOWN_REF(&pre->references, &i, pre->lock);
88     REF_PRINT_COUNT("EC_ec", pre);
89     if (i > 0)
90         return;
91     REF_ASSERT_ISNT(i < 0);
92
93     if (pre->points != NULL) {
94         EC_POINT **pts;
95
96         for (pts = pre->points; *pts != NULL; pts++)
97             EC_POINT_free(*pts);
98         OPENSSL_free(pre->points);
99     }
100     CRYPTO_THREAD_lock_free(pre->lock);
101     OPENSSL_free(pre);
102 }
103
104 #define EC_POINT_BN_set_flags(P, flags) do { \
105     BN_set_flags((P)->X, (flags)); \
106     BN_set_flags((P)->Y, (flags)); \
107     BN_set_flags((P)->Z, (flags)); \
108 } while(0)
109
110 /*-
111  * This functions computes (in constant time) a point multiplication over the
112  * EC group.
113  *
114  * At a high level, it is Montgomery ladder with conditional swaps.
115  *
116  * It performs either a fixed scalar point multiplication
117  *          (scalar * generator)
118  * when point is NULL, or a generic scalar point multiplication
119  *          (scalar * point)
120  * when point is not NULL.
121  *
122  * scalar should be in the range [0,n) otherwise all constant time bets are off.
123  *
124  * NB: This says nothing about EC_POINT_add and EC_POINT_dbl,
125  * which of course are not constant time themselves.
126  *
127  * The product is stored in r.
128  *
129  * Returns 1 on success, 0 otherwise.
130  */
131 static int ec_mul_consttime(const EC_GROUP *group, EC_POINT *r,
132                             const BIGNUM *scalar, const EC_POINT *point,
133                             BN_CTX *ctx)
134 {
135     int i, order_bits, group_top, kbit, pbit, Z_is_one;
136     EC_POINT *s = NULL;
137     BIGNUM *k = NULL;
138     BIGNUM *lambda = NULL;
139     BN_CTX *new_ctx = NULL;
140     int ret = 0;
141
142     if (ctx == NULL && (ctx = new_ctx = BN_CTX_secure_new()) == NULL)
143         goto err;
144
145     if ((group->order == NULL) || (group->field == NULL))
146         goto err;
147
148     order_bits = BN_num_bits(group->order);
149
150     s = EC_POINT_new(group);
151     if (s == NULL)
152         goto err;
153
154     if (point == NULL) {
155         if (group->generator == NULL)
156             goto err;
157         if (!EC_POINT_copy(s, group->generator))
158             goto err;
159     } else {
160         if (!EC_POINT_copy(s, point))
161             goto err;
162     }
163
164     EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME);
165
166     BN_CTX_start(ctx);
167     lambda = BN_CTX_get(ctx);
168     k = BN_CTX_get(ctx);
169     if (k == NULL)
170         goto err;
171
172     /*
173      * Group orders are often on a word boundary.
174      * So when we pad the scalar, some timing diff might
175      * pop if it needs to be expanded due to carries.
176      * So expand ahead of time.
177      */
178     group_top = bn_get_top(group->order);
179     if ((bn_wexpand(k, group_top + 1) == NULL)
180         || (bn_wexpand(lambda, group_top + 1) == NULL))
181         goto err;
182
183     if (!BN_copy(k, scalar))
184         goto err;
185
186     BN_set_flags(k, BN_FLG_CONSTTIME);
187
188     if ((BN_num_bits(k) > order_bits) || (BN_is_negative(k))) {
189         /*-
190          * this is an unusual input, and we don't guarantee
191          * constant-timeness
192          */
193         if (!BN_nnmod(k, k, group->order, ctx))
194             goto err;
195     }
196
197     if (!BN_add(lambda, k, group->order))
198         goto err;
199     BN_set_flags(lambda, BN_FLG_CONSTTIME);
200     if (!BN_add(k, lambda, group->order))
201         goto err;
202     /*
203      * lambda := scalar + order
204      * k := scalar + 2*order
205      */
206     kbit = BN_is_bit_set(lambda, order_bits);
207     BN_consttime_swap(kbit, k, lambda, group_top + 1);
208
209     group_top = bn_get_top(group->field);
210     if ((bn_wexpand(s->X, group_top) == NULL)
211         || (bn_wexpand(s->Y, group_top) == NULL)
212         || (bn_wexpand(s->Z, group_top) == NULL)
213         || (bn_wexpand(r->X, group_top) == NULL)
214         || (bn_wexpand(r->Y, group_top) == NULL)
215         || (bn_wexpand(r->Z, group_top) == NULL))
216         goto err;
217
218     /* top bit is a 1, in a fixed pos */
219     if (!EC_POINT_copy(r, s))
220         goto err;
221
222     EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME);
223
224     if (!EC_POINT_dbl(group, s, s, ctx))
225         goto err;
226
227     pbit = 0;
228
229 #define EC_POINT_CSWAP(c, a, b, w, t) do {         \
230         BN_consttime_swap(c, (a)->X, (b)->X, w);   \
231         BN_consttime_swap(c, (a)->Y, (b)->Y, w);   \
232         BN_consttime_swap(c, (a)->Z, (b)->Z, w);   \
233         t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \
234         (a)->Z_is_one ^= (t);                      \
235         (b)->Z_is_one ^= (t);                      \
236 } while(0)
237
238     /*-
239      * The ladder step, with branches, is
240      *
241      * k[i] == 0: S = add(R, S), R = dbl(R)
242      * k[i] == 1: R = add(S, R), S = dbl(S)
243      *
244      * Swapping R, S conditionally on k[i] leaves you with state
245      *
246      * k[i] == 0: T, U = R, S
247      * k[i] == 1: T, U = S, R
248      *
249      * Then perform the ECC ops.
250      *
251      * U = add(T, U)
252      * T = dbl(T)
253      *
254      * Which leaves you with state
255      *
256      * k[i] == 0: U = add(R, S), T = dbl(R)
257      * k[i] == 1: U = add(S, R), T = dbl(S)
258      *
259      * Swapping T, U conditionally on k[i] leaves you with state
260      *
261      * k[i] == 0: R, S = T, U
262      * k[i] == 1: R, S = U, T
263      *
264      * Which leaves you with state
265      *
266      * k[i] == 0: S = add(R, S), R = dbl(R)
267      * k[i] == 1: R = add(S, R), S = dbl(S)
268      *
269      * So we get the same logic, but instead of a branch it's a
270      * conditional swap, followed by ECC ops, then another conditional swap.
271      *
272      * Optimization: The end of iteration i and start of i-1 looks like
273      *
274      * ...
275      * CSWAP(k[i], R, S)
276      * ECC
277      * CSWAP(k[i], R, S)
278      * (next iteration)
279      * CSWAP(k[i-1], R, S)
280      * ECC
281      * CSWAP(k[i-1], R, S)
282      * ...
283      *
284      * So instead of two contiguous swaps, you can merge the condition
285      * bits and do a single swap.
286      *
287      * k[i]   k[i-1]    Outcome
288      * 0      0         No Swap
289      * 0      1         Swap
290      * 1      0         Swap
291      * 1      1         No Swap
292      *
293      * This is XOR. pbit tracks the previous bit of k.
294      */
295
296     for (i = order_bits - 1; i >= 0; i--) {
297         kbit = BN_is_bit_set(k, i) ^ pbit;
298         EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one);
299         if (!EC_POINT_add(group, s, r, s, ctx))
300             goto err;
301         if (!EC_POINT_dbl(group, r, r, ctx))
302             goto err;
303         /*
304          * pbit logic merges this cswap with that of the
305          * next iteration
306          */
307         pbit ^= kbit;
308     }
309     /* one final cswap to move the right value into r */
310     EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one);
311 #undef EC_POINT_CSWAP
312
313     ret = 1;
314
315  err:
316     EC_POINT_free(s);
317     BN_CTX_end(ctx);
318     BN_CTX_free(new_ctx);
319
320     return ret;
321 }
322
323 #undef EC_POINT_BN_set_flags
324
325 /*
326  * TODO: table should be optimised for the wNAF-based implementation,
327  * sometimes smaller windows will give better performance (thus the
328  * boundaries should be increased)
329  */
330 #define EC_window_bits_for_scalar_size(b) \
331                 ((size_t) \
332                  ((b) >= 2000 ? 6 : \
333                   (b) >=  800 ? 5 : \
334                   (b) >=  300 ? 4 : \
335                   (b) >=   70 ? 3 : \
336                   (b) >=   20 ? 2 : \
337                   1))
338
339 /*-
340  * Compute
341  *      \sum scalars[i]*points[i],
342  * also including
343  *      scalar*generator
344  * in the addition if scalar != NULL
345  */
346 int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
347                 size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
348                 BN_CTX *ctx)
349 {
350     BN_CTX *new_ctx = NULL;
351     const EC_POINT *generator = NULL;
352     EC_POINT *tmp = NULL;
353     size_t totalnum;
354     size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
355     size_t pre_points_per_block = 0;
356     size_t i, j;
357     int k;
358     int r_is_inverted = 0;
359     int r_is_at_infinity = 1;
360     size_t *wsize = NULL;       /* individual window sizes */
361     signed char **wNAF = NULL;  /* individual wNAFs */
362     size_t *wNAF_len = NULL;
363     size_t max_len = 0;
364     size_t num_val;
365     EC_POINT **val = NULL;      /* precomputation */
366     EC_POINT **v;
367     EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
368                                  * 'pre_comp->points' */
369     const EC_PRE_COMP *pre_comp = NULL;
370     int num_scalar = 0;         /* flag: will be set to 1 if 'scalar' must be
371                                  * treated like other scalars, i.e.
372                                  * precomputation is not available */
373     int ret = 0;
374
375     /*-
376      * Handle the common cases where the scalar is secret, enforcing a constant
377      * time scalar multiplication algorithm.
378      */
379     if ((scalar != NULL) && (num == 0)) {
380         /*-
381          * In this case we want to compute scalar * GeneratorPoint: this
382          * codepath is reached most prominently by (ephemeral) key generation
383          * of EC cryptosystems (i.e. ECDSA keygen and sign setup, ECDH
384          * keygen/first half), where the scalar is always secret. This is why
385          * we ignore if BN_FLG_CONSTTIME is actually set and we always call the
386          * constant time version.
387          */
388         return ec_mul_consttime(group, r, scalar, NULL, ctx);
389     }
390     if ((scalar == NULL) && (num == 1)) {
391         /*-
392          * In this case we want to compute scalar * GenericPoint: this codepath
393          * is reached most prominently by the second half of ECDH, where the
394          * secret scalar is multiplied by the peer's public point. To protect
395          * the secret scalar, we ignore if BN_FLG_CONSTTIME is actually set and
396          * we always call the constant time version.
397          */
398         return ec_mul_consttime(group, r, scalars[0], points[0], ctx);
399     }
400
401     if (group->meth != r->meth) {
402         ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
403         return 0;
404     }
405
406     if ((scalar == NULL) && (num == 0)) {
407         return EC_POINT_set_to_infinity(group, r);
408     }
409
410     for (i = 0; i < num; i++) {
411         if (group->meth != points[i]->meth) {
412             ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
413             return 0;
414         }
415     }
416
417     if (ctx == NULL) {
418         ctx = new_ctx = BN_CTX_new();
419         if (ctx == NULL)
420             goto err;
421     }
422
423     if (scalar != NULL) {
424         generator = EC_GROUP_get0_generator(group);
425         if (generator == NULL) {
426             ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR);
427             goto err;
428         }
429
430         /* look if we can use precomputed multiples of generator */
431
432         pre_comp = group->pre_comp.ec;
433         if (pre_comp && pre_comp->numblocks
434             && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) ==
435                 0)) {
436             blocksize = pre_comp->blocksize;
437
438             /*
439              * determine maximum number of blocks that wNAF splitting may
440              * yield (NB: maximum wNAF length is bit length plus one)
441              */
442             numblocks = (BN_num_bits(scalar) / blocksize) + 1;
443
444             /*
445              * we cannot use more blocks than we have precomputation for
446              */
447             if (numblocks > pre_comp->numblocks)
448                 numblocks = pre_comp->numblocks;
449
450             pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
451
452             /* check that pre_comp looks sane */
453             if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
454                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
455                 goto err;
456             }
457         } else {
458             /* can't use precomputation */
459             pre_comp = NULL;
460             numblocks = 1;
461             num_scalar = 1;     /* treat 'scalar' like 'num'-th element of
462                                  * 'scalars' */
463         }
464     }
465
466     totalnum = num + numblocks;
467
468     wsize = OPENSSL_malloc(totalnum * sizeof(wsize[0]));
469     wNAF_len = OPENSSL_malloc(totalnum * sizeof(wNAF_len[0]));
470     /* include space for pivot */
471     wNAF = OPENSSL_malloc((totalnum + 1) * sizeof(wNAF[0]));
472     val_sub = OPENSSL_malloc(totalnum * sizeof(val_sub[0]));
473
474     /* Ensure wNAF is initialised in case we end up going to err */
475     if (wNAF != NULL)
476         wNAF[0] = NULL;         /* preliminary pivot */
477
478     if (wsize == NULL || wNAF_len == NULL || wNAF == NULL || val_sub == NULL) {
479         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
480         goto err;
481     }
482
483     /*
484      * num_val will be the total number of temporarily precomputed points
485      */
486     num_val = 0;
487
488     for (i = 0; i < num + num_scalar; i++) {
489         size_t bits;
490
491         bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
492         wsize[i] = EC_window_bits_for_scalar_size(bits);
493         num_val += (size_t)1 << (wsize[i] - 1);
494         wNAF[i + 1] = NULL;     /* make sure we always have a pivot */
495         wNAF[i] =
496             bn_compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
497                             &wNAF_len[i]);
498         if (wNAF[i] == NULL)
499             goto err;
500         if (wNAF_len[i] > max_len)
501             max_len = wNAF_len[i];
502     }
503
504     if (numblocks) {
505         /* we go here iff scalar != NULL */
506
507         if (pre_comp == NULL) {
508             if (num_scalar != 1) {
509                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
510                 goto err;
511             }
512             /* we have already generated a wNAF for 'scalar' */
513         } else {
514             signed char *tmp_wNAF = NULL;
515             size_t tmp_len = 0;
516
517             if (num_scalar != 0) {
518                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
519                 goto err;
520             }
521
522             /*
523              * use the window size for which we have precomputation
524              */
525             wsize[num] = pre_comp->w;
526             tmp_wNAF = bn_compute_wNAF(scalar, wsize[num], &tmp_len);
527             if (!tmp_wNAF)
528                 goto err;
529
530             if (tmp_len <= max_len) {
531                 /*
532                  * One of the other wNAFs is at least as long as the wNAF
533                  * belonging to the generator, so wNAF splitting will not buy
534                  * us anything.
535                  */
536
537                 numblocks = 1;
538                 totalnum = num + 1; /* don't use wNAF splitting */
539                 wNAF[num] = tmp_wNAF;
540                 wNAF[num + 1] = NULL;
541                 wNAF_len[num] = tmp_len;
542                 /*
543                  * pre_comp->points starts with the points that we need here:
544                  */
545                 val_sub[num] = pre_comp->points;
546             } else {
547                 /*
548                  * don't include tmp_wNAF directly into wNAF array - use wNAF
549                  * splitting and include the blocks
550                  */
551
552                 signed char *pp;
553                 EC_POINT **tmp_points;
554
555                 if (tmp_len < numblocks * blocksize) {
556                     /*
557                      * possibly we can do with fewer blocks than estimated
558                      */
559                     numblocks = (tmp_len + blocksize - 1) / blocksize;
560                     if (numblocks > pre_comp->numblocks) {
561                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
562                         OPENSSL_free(tmp_wNAF);
563                         goto err;
564                     }
565                     totalnum = num + numblocks;
566                 }
567
568                 /* split wNAF in 'numblocks' parts */
569                 pp = tmp_wNAF;
570                 tmp_points = pre_comp->points;
571
572                 for (i = num; i < totalnum; i++) {
573                     if (i < totalnum - 1) {
574                         wNAF_len[i] = blocksize;
575                         if (tmp_len < blocksize) {
576                             ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
577                             OPENSSL_free(tmp_wNAF);
578                             goto err;
579                         }
580                         tmp_len -= blocksize;
581                     } else
582                         /*
583                          * last block gets whatever is left (this could be
584                          * more or less than 'blocksize'!)
585                          */
586                         wNAF_len[i] = tmp_len;
587
588                     wNAF[i + 1] = NULL;
589                     wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
590                     if (wNAF[i] == NULL) {
591                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
592                         OPENSSL_free(tmp_wNAF);
593                         goto err;
594                     }
595                     memcpy(wNAF[i], pp, wNAF_len[i]);
596                     if (wNAF_len[i] > max_len)
597                         max_len = wNAF_len[i];
598
599                     if (*tmp_points == NULL) {
600                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
601                         OPENSSL_free(tmp_wNAF);
602                         goto err;
603                     }
604                     val_sub[i] = tmp_points;
605                     tmp_points += pre_points_per_block;
606                     pp += blocksize;
607                 }
608                 OPENSSL_free(tmp_wNAF);
609             }
610         }
611     }
612
613     /*
614      * All points we precompute now go into a single array 'val'.
615      * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
616      * subarray of 'pre_comp->points' if we already have precomputation.
617      */
618     val = OPENSSL_malloc((num_val + 1) * sizeof(val[0]));
619     if (val == NULL) {
620         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
621         goto err;
622     }
623     val[num_val] = NULL;        /* pivot element */
624
625     /* allocate points for precomputation */
626     v = val;
627     for (i = 0; i < num + num_scalar; i++) {
628         val_sub[i] = v;
629         for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
630             *v = EC_POINT_new(group);
631             if (*v == NULL)
632                 goto err;
633             v++;
634         }
635     }
636     if (!(v == val + num_val)) {
637         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
638         goto err;
639     }
640
641     if ((tmp = EC_POINT_new(group)) == NULL)
642         goto err;
643
644     /*-
645      * prepare precomputed values:
646      *    val_sub[i][0] :=     points[i]
647      *    val_sub[i][1] := 3 * points[i]
648      *    val_sub[i][2] := 5 * points[i]
649      *    ...
650      */
651     for (i = 0; i < num + num_scalar; i++) {
652         if (i < num) {
653             if (!EC_POINT_copy(val_sub[i][0], points[i]))
654                 goto err;
655         } else {
656             if (!EC_POINT_copy(val_sub[i][0], generator))
657                 goto err;
658         }
659
660         if (wsize[i] > 1) {
661             if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
662                 goto err;
663             for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
664                 if (!EC_POINT_add
665                     (group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
666                     goto err;
667             }
668         }
669     }
670
671     if (!EC_POINTs_make_affine(group, num_val, val, ctx))
672         goto err;
673
674     r_is_at_infinity = 1;
675
676     for (k = max_len - 1; k >= 0; k--) {
677         if (!r_is_at_infinity) {
678             if (!EC_POINT_dbl(group, r, r, ctx))
679                 goto err;
680         }
681
682         for (i = 0; i < totalnum; i++) {
683             if (wNAF_len[i] > (size_t)k) {
684                 int digit = wNAF[i][k];
685                 int is_neg;
686
687                 if (digit) {
688                     is_neg = digit < 0;
689
690                     if (is_neg)
691                         digit = -digit;
692
693                     if (is_neg != r_is_inverted) {
694                         if (!r_is_at_infinity) {
695                             if (!EC_POINT_invert(group, r, ctx))
696                                 goto err;
697                         }
698                         r_is_inverted = !r_is_inverted;
699                     }
700
701                     /* digit > 0 */
702
703                     if (r_is_at_infinity) {
704                         if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
705                             goto err;
706                         r_is_at_infinity = 0;
707                     } else {
708                         if (!EC_POINT_add
709                             (group, r, r, val_sub[i][digit >> 1], ctx))
710                             goto err;
711                     }
712                 }
713             }
714         }
715     }
716
717     if (r_is_at_infinity) {
718         if (!EC_POINT_set_to_infinity(group, r))
719             goto err;
720     } else {
721         if (r_is_inverted)
722             if (!EC_POINT_invert(group, r, ctx))
723                 goto err;
724     }
725
726     ret = 1;
727
728  err:
729     BN_CTX_free(new_ctx);
730     EC_POINT_free(tmp);
731     OPENSSL_free(wsize);
732     OPENSSL_free(wNAF_len);
733     if (wNAF != NULL) {
734         signed char **w;
735
736         for (w = wNAF; *w != NULL; w++)
737             OPENSSL_free(*w);
738
739         OPENSSL_free(wNAF);
740     }
741     if (val != NULL) {
742         for (v = val; *v != NULL; v++)
743             EC_POINT_clear_free(*v);
744
745         OPENSSL_free(val);
746     }
747     OPENSSL_free(val_sub);
748     return ret;
749 }
750
751 /*-
752  * ec_wNAF_precompute_mult()
753  * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
754  * for use with wNAF splitting as implemented in ec_wNAF_mul().
755  *
756  * 'pre_comp->points' is an array of multiples of the generator
757  * of the following form:
758  * points[0] =     generator;
759  * points[1] = 3 * generator;
760  * ...
761  * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
762  * points[2^(w-1)]   =     2^blocksize * generator;
763  * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
764  * ...
765  * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) * generator
766  * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) * generator
767  * ...
768  * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) * generator
769  * points[2^(w-1)*numblocks]       = NULL
770  */
771 int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
772 {
773     const EC_POINT *generator;
774     EC_POINT *tmp_point = NULL, *base = NULL, **var;
775     BN_CTX *new_ctx = NULL;
776     const BIGNUM *order;
777     size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
778     EC_POINT **points = NULL;
779     EC_PRE_COMP *pre_comp;
780     int ret = 0;
781
782     /* if there is an old EC_PRE_COMP object, throw it away */
783     EC_pre_comp_free(group);
784     if ((pre_comp = ec_pre_comp_new(group)) == NULL)
785         return 0;
786
787     generator = EC_GROUP_get0_generator(group);
788     if (generator == NULL) {
789         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
790         goto err;
791     }
792
793     if (ctx == NULL) {
794         ctx = new_ctx = BN_CTX_new();
795         if (ctx == NULL)
796             goto err;
797     }
798
799     BN_CTX_start(ctx);
800
801     order = EC_GROUP_get0_order(group);
802     if (order == NULL)
803         goto err;
804     if (BN_is_zero(order)) {
805         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
806         goto err;
807     }
808
809     bits = BN_num_bits(order);
810     /*
811      * The following parameters mean we precompute (approximately) one point
812      * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
813      * bit lengths, other parameter combinations might provide better
814      * efficiency.
815      */
816     blocksize = 8;
817     w = 4;
818     if (EC_window_bits_for_scalar_size(bits) > w) {
819         /* let's not make the window too small ... */
820         w = EC_window_bits_for_scalar_size(bits);
821     }
822
823     numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
824                                                      * to use for wNAF
825                                                      * splitting */
826
827     pre_points_per_block = (size_t)1 << (w - 1);
828     num = pre_points_per_block * numblocks; /* number of points to compute
829                                              * and store */
830
831     points = OPENSSL_malloc(sizeof(*points) * (num + 1));
832     if (points == NULL) {
833         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
834         goto err;
835     }
836
837     var = points;
838     var[num] = NULL;            /* pivot */
839     for (i = 0; i < num; i++) {
840         if ((var[i] = EC_POINT_new(group)) == NULL) {
841             ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
842             goto err;
843         }
844     }
845
846     if ((tmp_point = EC_POINT_new(group)) == NULL
847         || (base = EC_POINT_new(group)) == NULL) {
848         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
849         goto err;
850     }
851
852     if (!EC_POINT_copy(base, generator))
853         goto err;
854
855     /* do the precomputation */
856     for (i = 0; i < numblocks; i++) {
857         size_t j;
858
859         if (!EC_POINT_dbl(group, tmp_point, base, ctx))
860             goto err;
861
862         if (!EC_POINT_copy(*var++, base))
863             goto err;
864
865         for (j = 1; j < pre_points_per_block; j++, var++) {
866             /*
867              * calculate odd multiples of the current base point
868              */
869             if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
870                 goto err;
871         }
872
873         if (i < numblocks - 1) {
874             /*
875              * get the next base (multiply current one by 2^blocksize)
876              */
877             size_t k;
878
879             if (blocksize <= 2) {
880                 ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_INTERNAL_ERROR);
881                 goto err;
882             }
883
884             if (!EC_POINT_dbl(group, base, tmp_point, ctx))
885                 goto err;
886             for (k = 2; k < blocksize; k++) {
887                 if (!EC_POINT_dbl(group, base, base, ctx))
888                     goto err;
889             }
890         }
891     }
892
893     if (!EC_POINTs_make_affine(group, num, points, ctx))
894         goto err;
895
896     pre_comp->group = group;
897     pre_comp->blocksize = blocksize;
898     pre_comp->numblocks = numblocks;
899     pre_comp->w = w;
900     pre_comp->points = points;
901     points = NULL;
902     pre_comp->num = num;
903     SETPRECOMP(group, ec, pre_comp);
904     pre_comp = NULL;
905     ret = 1;
906
907  err:
908     if (ctx != NULL)
909         BN_CTX_end(ctx);
910     BN_CTX_free(new_ctx);
911     EC_ec_pre_comp_free(pre_comp);
912     if (points) {
913         EC_POINT **p;
914
915         for (p = points; *p != NULL; p++)
916             EC_POINT_free(*p);
917         OPENSSL_free(points);
918     }
919     EC_POINT_free(tmp_point);
920     EC_POINT_free(base);
921     return ret;
922 }
923
924 int ec_wNAF_have_precompute_mult(const EC_GROUP *group)
925 {
926     return HAVEPRECOMP(group, ec);
927 }