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