Copyright consolidation 06/10
[openssl.git] / crypto / ec / ec_mult.c
1 /*
2  * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  * Portions of this software developed by SUN MICROSYSTEMS, INC.,
13  * and contributed to the OpenSSL project.
14  */
15
16 #include <string.h>
17 #include <openssl/err.h>
18
19 #include "internal/cryptlib.h"
20 #include "internal/bn_int.h"
21 #include "ec_lcl.h"
22
23 /*
24  * This file implements the wNAF-based interleaving multi-exponentiation method
25  * (<URL:http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp>);
26  * for multiplication with precomputation, we use wNAF splitting
27  * (<URL: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     int 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_atomic_add(&pre->references, 1, &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_atomic_add(&pre->references, -1, &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 /*
105  * TODO: table should be optimised for the wNAF-based implementation,
106  * sometimes smaller windows will give better performance (thus the
107  * boundaries should be increased)
108  */
109 #define EC_window_bits_for_scalar_size(b) \
110                 ((size_t) \
111                  ((b) >= 2000 ? 6 : \
112                   (b) >=  800 ? 5 : \
113                   (b) >=  300 ? 4 : \
114                   (b) >=   70 ? 3 : \
115                   (b) >=   20 ? 2 : \
116                   1))
117
118 /*-
119  * Compute
120  *      \sum scalars[i]*points[i],
121  * also including
122  *      scalar*generator
123  * in the addition if scalar != NULL
124  */
125 int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
126                 size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
127                 BN_CTX *ctx)
128 {
129     BN_CTX *new_ctx = NULL;
130     const EC_POINT *generator = NULL;
131     EC_POINT *tmp = NULL;
132     size_t totalnum;
133     size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
134     size_t pre_points_per_block = 0;
135     size_t i, j;
136     int k;
137     int r_is_inverted = 0;
138     int r_is_at_infinity = 1;
139     size_t *wsize = NULL;       /* individual window sizes */
140     signed char **wNAF = NULL;  /* individual wNAFs */
141     size_t *wNAF_len = NULL;
142     size_t max_len = 0;
143     size_t num_val;
144     EC_POINT **val = NULL;      /* precomputation */
145     EC_POINT **v;
146     EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
147                                  * 'pre_comp->points' */
148     const EC_PRE_COMP *pre_comp = NULL;
149     int num_scalar = 0;         /* flag: will be set to 1 if 'scalar' must be
150                                  * treated like other scalars, i.e.
151                                  * precomputation is not available */
152     int ret = 0;
153
154     if (group->meth != r->meth) {
155         ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
156         return 0;
157     }
158
159     if ((scalar == NULL) && (num == 0)) {
160         return EC_POINT_set_to_infinity(group, r);
161     }
162
163     for (i = 0; i < num; i++) {
164         if (group->meth != points[i]->meth) {
165             ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
166             return 0;
167         }
168     }
169
170     if (ctx == NULL) {
171         ctx = new_ctx = BN_CTX_new();
172         if (ctx == NULL)
173             goto err;
174     }
175
176     if (scalar != NULL) {
177         generator = EC_GROUP_get0_generator(group);
178         if (generator == NULL) {
179             ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR);
180             goto err;
181         }
182
183         /* look if we can use precomputed multiples of generator */
184
185         pre_comp = group->pre_comp.ec;
186         if (pre_comp && pre_comp->numblocks
187             && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) ==
188                 0)) {
189             blocksize = pre_comp->blocksize;
190
191             /*
192              * determine maximum number of blocks that wNAF splitting may
193              * yield (NB: maximum wNAF length is bit length plus one)
194              */
195             numblocks = (BN_num_bits(scalar) / blocksize) + 1;
196
197             /*
198              * we cannot use more blocks than we have precomputation for
199              */
200             if (numblocks > pre_comp->numblocks)
201                 numblocks = pre_comp->numblocks;
202
203             pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
204
205             /* check that pre_comp looks sane */
206             if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
207                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
208                 goto err;
209             }
210         } else {
211             /* can't use precomputation */
212             pre_comp = NULL;
213             numblocks = 1;
214             num_scalar = 1;     /* treat 'scalar' like 'num'-th element of
215                                  * 'scalars' */
216         }
217     }
218
219     totalnum = num + numblocks;
220
221     wsize = OPENSSL_malloc(totalnum * sizeof wsize[0]);
222     wNAF_len = OPENSSL_malloc(totalnum * sizeof wNAF_len[0]);
223     wNAF = OPENSSL_malloc((totalnum + 1) * sizeof wNAF[0]); /* includes space
224                                                              * for pivot */
225     val_sub = OPENSSL_malloc(totalnum * sizeof val_sub[0]);
226
227     /* Ensure wNAF is initialised in case we end up going to err */
228     if (wNAF != NULL)
229         wNAF[0] = NULL;         /* preliminary pivot */
230
231     if (wsize == NULL || wNAF_len == NULL || wNAF == NULL || val_sub == NULL) {
232         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
233         goto err;
234     }
235
236     /*
237      * num_val will be the total number of temporarily precomputed points
238      */
239     num_val = 0;
240
241     for (i = 0; i < num + num_scalar; i++) {
242         size_t bits;
243
244         bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
245         wsize[i] = EC_window_bits_for_scalar_size(bits);
246         num_val += (size_t)1 << (wsize[i] - 1);
247         wNAF[i + 1] = NULL;     /* make sure we always have a pivot */
248         wNAF[i] =
249             bn_compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
250                             &wNAF_len[i]);
251         if (wNAF[i] == NULL)
252             goto err;
253         if (wNAF_len[i] > max_len)
254             max_len = wNAF_len[i];
255     }
256
257     if (numblocks) {
258         /* we go here iff scalar != NULL */
259
260         if (pre_comp == NULL) {
261             if (num_scalar != 1) {
262                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
263                 goto err;
264             }
265             /* we have already generated a wNAF for 'scalar' */
266         } else {
267             signed char *tmp_wNAF = NULL;
268             size_t tmp_len = 0;
269
270             if (num_scalar != 0) {
271                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
272                 goto err;
273             }
274
275             /*
276              * use the window size for which we have precomputation
277              */
278             wsize[num] = pre_comp->w;
279             tmp_wNAF = bn_compute_wNAF(scalar, wsize[num], &tmp_len);
280             if (!tmp_wNAF)
281                 goto err;
282
283             if (tmp_len <= max_len) {
284                 /*
285                  * One of the other wNAFs is at least as long as the wNAF
286                  * belonging to the generator, so wNAF splitting will not buy
287                  * us anything.
288                  */
289
290                 numblocks = 1;
291                 totalnum = num + 1; /* don't use wNAF splitting */
292                 wNAF[num] = tmp_wNAF;
293                 wNAF[num + 1] = NULL;
294                 wNAF_len[num] = tmp_len;
295                 /*
296                  * pre_comp->points starts with the points that we need here:
297                  */
298                 val_sub[num] = pre_comp->points;
299             } else {
300                 /*
301                  * don't include tmp_wNAF directly into wNAF array - use wNAF
302                  * splitting and include the blocks
303                  */
304
305                 signed char *pp;
306                 EC_POINT **tmp_points;
307
308                 if (tmp_len < numblocks * blocksize) {
309                     /*
310                      * possibly we can do with fewer blocks than estimated
311                      */
312                     numblocks = (tmp_len + blocksize - 1) / blocksize;
313                     if (numblocks > pre_comp->numblocks) {
314                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
315                         goto err;
316                     }
317                     totalnum = num + numblocks;
318                 }
319
320                 /* split wNAF in 'numblocks' parts */
321                 pp = tmp_wNAF;
322                 tmp_points = pre_comp->points;
323
324                 for (i = num; i < totalnum; i++) {
325                     if (i < totalnum - 1) {
326                         wNAF_len[i] = blocksize;
327                         if (tmp_len < blocksize) {
328                             ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
329                             goto err;
330                         }
331                         tmp_len -= blocksize;
332                     } else
333                         /*
334                          * last block gets whatever is left (this could be
335                          * more or less than 'blocksize'!)
336                          */
337                         wNAF_len[i] = tmp_len;
338
339                     wNAF[i + 1] = NULL;
340                     wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
341                     if (wNAF[i] == NULL) {
342                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
343                         OPENSSL_free(tmp_wNAF);
344                         goto err;
345                     }
346                     memcpy(wNAF[i], pp, wNAF_len[i]);
347                     if (wNAF_len[i] > max_len)
348                         max_len = wNAF_len[i];
349
350                     if (*tmp_points == NULL) {
351                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
352                         OPENSSL_free(tmp_wNAF);
353                         goto err;
354                     }
355                     val_sub[i] = tmp_points;
356                     tmp_points += pre_points_per_block;
357                     pp += blocksize;
358                 }
359                 OPENSSL_free(tmp_wNAF);
360             }
361         }
362     }
363
364     /*
365      * All points we precompute now go into a single array 'val'.
366      * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
367      * subarray of 'pre_comp->points' if we already have precomputation.
368      */
369     val = OPENSSL_malloc((num_val + 1) * sizeof val[0]);
370     if (val == NULL) {
371         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
372         goto err;
373     }
374     val[num_val] = NULL;        /* pivot element */
375
376     /* allocate points for precomputation */
377     v = val;
378     for (i = 0; i < num + num_scalar; i++) {
379         val_sub[i] = v;
380         for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
381             *v = EC_POINT_new(group);
382             if (*v == NULL)
383                 goto err;
384             v++;
385         }
386     }
387     if (!(v == val + num_val)) {
388         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
389         goto err;
390     }
391
392     if ((tmp = EC_POINT_new(group)) == NULL)
393         goto err;
394
395     /*-
396      * prepare precomputed values:
397      *    val_sub[i][0] :=     points[i]
398      *    val_sub[i][1] := 3 * points[i]
399      *    val_sub[i][2] := 5 * points[i]
400      *    ...
401      */
402     for (i = 0; i < num + num_scalar; i++) {
403         if (i < num) {
404             if (!EC_POINT_copy(val_sub[i][0], points[i]))
405                 goto err;
406         } else {
407             if (!EC_POINT_copy(val_sub[i][0], generator))
408                 goto err;
409         }
410
411         if (wsize[i] > 1) {
412             if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
413                 goto err;
414             for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
415                 if (!EC_POINT_add
416                     (group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
417                     goto err;
418             }
419         }
420     }
421
422     if (!EC_POINTs_make_affine(group, num_val, val, ctx))
423         goto err;
424
425     r_is_at_infinity = 1;
426
427     for (k = max_len - 1; k >= 0; k--) {
428         if (!r_is_at_infinity) {
429             if (!EC_POINT_dbl(group, r, r, ctx))
430                 goto err;
431         }
432
433         for (i = 0; i < totalnum; i++) {
434             if (wNAF_len[i] > (size_t)k) {
435                 int digit = wNAF[i][k];
436                 int is_neg;
437
438                 if (digit) {
439                     is_neg = digit < 0;
440
441                     if (is_neg)
442                         digit = -digit;
443
444                     if (is_neg != r_is_inverted) {
445                         if (!r_is_at_infinity) {
446                             if (!EC_POINT_invert(group, r, ctx))
447                                 goto err;
448                         }
449                         r_is_inverted = !r_is_inverted;
450                     }
451
452                     /* digit > 0 */
453
454                     if (r_is_at_infinity) {
455                         if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
456                             goto err;
457                         r_is_at_infinity = 0;
458                     } else {
459                         if (!EC_POINT_add
460                             (group, r, r, val_sub[i][digit >> 1], ctx))
461                             goto err;
462                     }
463                 }
464             }
465         }
466     }
467
468     if (r_is_at_infinity) {
469         if (!EC_POINT_set_to_infinity(group, r))
470             goto err;
471     } else {
472         if (r_is_inverted)
473             if (!EC_POINT_invert(group, r, ctx))
474                 goto err;
475     }
476
477     ret = 1;
478
479  err:
480     BN_CTX_free(new_ctx);
481     EC_POINT_free(tmp);
482     OPENSSL_free(wsize);
483     OPENSSL_free(wNAF_len);
484     if (wNAF != NULL) {
485         signed char **w;
486
487         for (w = wNAF; *w != NULL; w++)
488             OPENSSL_free(*w);
489
490         OPENSSL_free(wNAF);
491     }
492     if (val != NULL) {
493         for (v = val; *v != NULL; v++)
494             EC_POINT_clear_free(*v);
495
496         OPENSSL_free(val);
497     }
498     OPENSSL_free(val_sub);
499     return ret;
500 }
501
502 /*-
503  * ec_wNAF_precompute_mult()
504  * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
505  * for use with wNAF splitting as implemented in ec_wNAF_mul().
506  *
507  * 'pre_comp->points' is an array of multiples of the generator
508  * of the following form:
509  * points[0] =     generator;
510  * points[1] = 3 * generator;
511  * ...
512  * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
513  * points[2^(w-1)]   =     2^blocksize * generator;
514  * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
515  * ...
516  * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) * generator
517  * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) * generator
518  * ...
519  * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) * generator
520  * points[2^(w-1)*numblocks]       = NULL
521  */
522 int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
523 {
524     const EC_POINT *generator;
525     EC_POINT *tmp_point = NULL, *base = NULL, **var;
526     BN_CTX *new_ctx = NULL;
527     const BIGNUM *order;
528     size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
529     EC_POINT **points = NULL;
530     EC_PRE_COMP *pre_comp;
531     int ret = 0;
532
533     /* if there is an old EC_PRE_COMP object, throw it away */
534     EC_pre_comp_free(group);
535     if ((pre_comp = ec_pre_comp_new(group)) == NULL)
536         return 0;
537
538     generator = EC_GROUP_get0_generator(group);
539     if (generator == NULL) {
540         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
541         goto err;
542     }
543
544     if (ctx == NULL) {
545         ctx = new_ctx = BN_CTX_new();
546         if (ctx == NULL)
547             goto err;
548     }
549
550     BN_CTX_start(ctx);
551
552     order = EC_GROUP_get0_order(group);
553     if (order == NULL)
554         goto err;
555     if (BN_is_zero(order)) {
556         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
557         goto err;
558     }
559
560     bits = BN_num_bits(order);
561     /*
562      * The following parameters mean we precompute (approximately) one point
563      * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
564      * bit lengths, other parameter combinations might provide better
565      * efficiency.
566      */
567     blocksize = 8;
568     w = 4;
569     if (EC_window_bits_for_scalar_size(bits) > w) {
570         /* let's not make the window too small ... */
571         w = EC_window_bits_for_scalar_size(bits);
572     }
573
574     numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
575                                                      * to use for wNAF
576                                                      * splitting */
577
578     pre_points_per_block = (size_t)1 << (w - 1);
579     num = pre_points_per_block * numblocks; /* number of points to compute
580                                              * and store */
581
582     points = OPENSSL_malloc(sizeof(*points) * (num + 1));
583     if (points == NULL) {
584         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
585         goto err;
586     }
587
588     var = points;
589     var[num] = NULL;            /* pivot */
590     for (i = 0; i < num; i++) {
591         if ((var[i] = EC_POINT_new(group)) == NULL) {
592             ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
593             goto err;
594         }
595     }
596
597     if ((tmp_point = EC_POINT_new(group)) == NULL
598         || (base = EC_POINT_new(group)) == NULL) {
599         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
600         goto err;
601     }
602
603     if (!EC_POINT_copy(base, generator))
604         goto err;
605
606     /* do the precomputation */
607     for (i = 0; i < numblocks; i++) {
608         size_t j;
609
610         if (!EC_POINT_dbl(group, tmp_point, base, ctx))
611             goto err;
612
613         if (!EC_POINT_copy(*var++, base))
614             goto err;
615
616         for (j = 1; j < pre_points_per_block; j++, var++) {
617             /*
618              * calculate odd multiples of the current base point
619              */
620             if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
621                 goto err;
622         }
623
624         if (i < numblocks - 1) {
625             /*
626              * get the next base (multiply current one by 2^blocksize)
627              */
628             size_t k;
629
630             if (blocksize <= 2) {
631                 ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_INTERNAL_ERROR);
632                 goto err;
633             }
634
635             if (!EC_POINT_dbl(group, base, tmp_point, ctx))
636                 goto err;
637             for (k = 2; k < blocksize; k++) {
638                 if (!EC_POINT_dbl(group, base, base, ctx))
639                     goto err;
640             }
641         }
642     }
643
644     if (!EC_POINTs_make_affine(group, num, points, ctx))
645         goto err;
646
647     pre_comp->group = group;
648     pre_comp->blocksize = blocksize;
649     pre_comp->numblocks = numblocks;
650     pre_comp->w = w;
651     pre_comp->points = points;
652     points = NULL;
653     pre_comp->num = num;
654     SETPRECOMP(group, ec, pre_comp);
655     pre_comp = NULL;
656     ret = 1;
657
658  err:
659     if (ctx != NULL)
660         BN_CTX_end(ctx);
661     BN_CTX_free(new_ctx);
662     EC_ec_pre_comp_free(pre_comp);
663     if (points) {
664         EC_POINT **p;
665
666         for (p = points; *p != NULL; p++)
667             EC_POINT_free(*p);
668         OPENSSL_free(points);
669     }
670     EC_POINT_free(tmp_point);
671     EC_POINT_free(base);
672     return ret;
673 }
674
675 int ec_wNAF_have_precompute_mult(const EC_GROUP *group)
676 {
677     return HAVEPRECOMP(group, ec);
678 }