add support for elliptic curves over binary fields
[openssl.git] / crypto / ec / ec_mult.c
1 /* crypto/ec/ec_mult.c */
2 /* ====================================================================
3  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer. 
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55 /* ====================================================================
56  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
57  * Portions of this software developed by SUN MICROSYSTEMS, INC.,
58  * and contributed to the OpenSSL project.
59  */
60
61 #include <openssl/err.h>
62
63 #include "ec_lcl.h"
64
65
66 /* TODO: optional precomputation of multiples of the generator */
67
68
69
70 /*
71  * wNAF-based interleaving multi-exponentation method
72  * (<URL:http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp>)
73  */
74
75
76 /* Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'.
77  * This is an array  r[]  of values that are either zero or odd with an
78  * absolute value less than  2^w  satisfying
79  *     scalar = \sum_j r[j]*2^j
80  * where at most one of any  w+1  consecutive digits is non-zero
81  * with the exception that the most significant digit may be only
82  * w-1 zeros away from that next non-zero digit.
83  */
84 static signed char *compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len)
85         {
86         int window_val;
87         int ok = 0;
88         signed char *r = NULL;
89         int sign = 1;
90         int bit, next_bit, mask;
91         size_t len = 0, j;
92         
93         if (w <= 0 || w > 7) /* 'signed char' can represent integers with absolute values less than 2^7 */
94                 {
95                 ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
96                 goto err;
97                 }
98         bit = 1 << w; /* at most 128 */
99         next_bit = bit << 1; /* at most 256 */
100         mask = next_bit - 1; /* at most 255 */
101
102         if (scalar->neg)
103                 {
104                 sign = -1;
105                 }
106
107         len = BN_num_bits(scalar);
108         r = OPENSSL_malloc(len + 1); /* modified wNAF may be one digit longer than binary representation */
109         if (r == NULL) goto err;
110
111         if (scalar->d == NULL || scalar->top == 0)
112                 {
113                 ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
114                 goto err;
115                 }
116         window_val = scalar->d[0] & mask;
117         j = 0;
118         while ((window_val != 0) || (j + w + 1 < len)) /* if j+w+1 >= len, window_val will not increase */
119                 {
120                 int digit = 0;
121
122                 /* 0 <= window_val <= 2^(w+1) */
123
124                 if (window_val & 1)
125                         {
126                         /* 0 < window_val < 2^(w+1) */
127
128                         if (window_val & bit)
129                                 {
130                                 digit = window_val - next_bit; /* -2^w < digit < 0 */
131
132 #if 1 /* modified wNAF */
133                                 if (j + w + 1 >= len)
134                                         {
135                                         /* special case for generating modified wNAFs:
136                                          * no new bits will be added into window_val,
137                                          * so using a positive digit here will decrease
138                                          * the total length of the representation */
139                                         
140                                         digit = window_val & (mask >> 1); /* 0 < digit < 2^w */
141                                         }
142 #endif
143                                 }
144                         else
145                                 {
146                                 digit = window_val; /* 0 < digit < 2^w */
147                                 }
148                         
149                         if (digit <= -bit || digit >= bit || !(digit & 1))
150                                 {
151                                 ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
152                                 goto err;
153                                 }
154
155                         window_val -= digit;
156
157                         /* now window_val is 0 or 2^(w+1) in standard wNAF generation;
158                          * for modified window NAFs, it may also be 2^w
159                          */
160                         if (window_val != 0 && window_val != next_bit && window_val != bit)
161                                 {
162                                 ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
163                                 goto err;
164                                 }
165                         }
166
167                 r[j++] = sign * digit;
168
169                 window_val >>= 1;
170                 window_val += bit * BN_is_bit_set(scalar, j + w);
171
172                 if (window_val > next_bit)
173                         {
174                         ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
175                         goto err;
176                         }
177                 }
178
179         if (j > len + 1)
180                 {
181                 ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
182                 goto err;
183                 }
184         len = j;
185         ok = 1;
186
187  err:
188         if (!ok)
189                 {
190                 OPENSSL_free(r);
191                 r = NULL;
192                 }
193         if (ok)
194                 *ret_len = len;
195         return r;
196         }
197
198
199 /* TODO: table should be optimised for the wNAF-based implementation,
200  *       sometimes smaller windows will give better performance
201  *       (thus the boundaries should be increased)
202  */
203 #define EC_window_bits_for_scalar_size(b) \
204                 ((b) >= 2000 ? 6 : \
205                  (b) >=  800 ? 5 : \
206                  (b) >=  300 ? 4 : \
207                  (b) >=   70 ? 3 : \
208                  (b) >=   20 ? 2 : \
209                   1)
210
211 /* Compute
212  *      \sum scalars[i]*points[i],
213  * also including
214  *      scalar*generator
215  * in the addition if scalar != NULL
216  */
217 int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
218         size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx)
219         {
220         BN_CTX *new_ctx = NULL;
221         EC_POINT *generator = NULL;
222         EC_POINT *tmp = NULL;
223         size_t totalnum;
224         size_t i, j;
225         int k;
226         int r_is_inverted = 0;
227         int r_is_at_infinity = 1;
228         size_t *wsize = NULL; /* individual window sizes */
229         signed char **wNAF = NULL; /* individual wNAFs */
230         size_t *wNAF_len = NULL;
231         size_t max_len = 0;
232         size_t num_val;
233         EC_POINT **val = NULL; /* precomputation */
234         EC_POINT **v;
235         EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' */
236         int ret = 0;
237         
238         if (scalar != NULL)
239                 {
240                 generator = EC_GROUP_get0_generator(group);
241                 if (generator == NULL)
242                         {
243                         ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR);
244                         return 0;
245                         }
246                 }
247         
248         for (i = 0; i < num; i++)
249                 {
250                 if (group->meth != points[i]->meth)
251                         {
252                         ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
253                         return 0;
254                         }
255                 }
256
257         totalnum = num + (scalar != NULL);
258
259         wsize = OPENSSL_malloc(totalnum * sizeof wsize[0]);
260         wNAF_len = OPENSSL_malloc(totalnum * sizeof wNAF_len[0]);
261         wNAF = OPENSSL_malloc((totalnum + 1) * sizeof wNAF[0]);
262         if (wNAF != NULL)
263                 {
264                 wNAF[0] = NULL; /* preliminary pivot */
265                 }
266         if (wsize == NULL || wNAF_len == NULL || wNAF == NULL) goto err;
267
268         /* num_val := total number of points to precompute */
269         num_val = 0;
270         for (i = 0; i < totalnum; i++)
271                 {
272                 size_t bits;
273
274                 bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
275                 wsize[i] = EC_window_bits_for_scalar_size(bits);
276                 num_val += 1u << (wsize[i] - 1);
277                 }
278
279         /* all precomputed points go into a single array 'val',
280          * 'val_sub[i]' is a pointer to the subarray for the i-th point */
281         val = OPENSSL_malloc((num_val + 1) * sizeof val[0]);
282         if (val == NULL) goto err;
283         val[num_val] = NULL; /* pivot element */
284
285         val_sub = OPENSSL_malloc(totalnum * sizeof val_sub[0]);
286         if (val_sub == NULL) goto err;
287
288         /* allocate points for precomputation */
289         v = val;
290         for (i = 0; i < totalnum; i++)
291                 {
292                 val_sub[i] = v;
293                 for (j = 0; j < (1u << (wsize[i] - 1)); j++)
294                         {
295                         *v = EC_POINT_new(group);
296                         if (*v == NULL) goto err;
297                         v++;
298                         }
299                 }
300         if (!(v == val + num_val))
301                 {
302                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
303                 goto err;
304                 }
305
306         if (ctx == NULL)
307                 {
308                 ctx = new_ctx = BN_CTX_new();
309                 if (ctx == NULL)
310                         goto err;
311                 }
312         
313         tmp = EC_POINT_new(group);
314         if (tmp == NULL) goto err;
315
316         /* prepare precomputed values:
317          *    val_sub[i][0] :=     points[i]
318          *    val_sub[i][1] := 3 * points[i]
319          *    val_sub[i][2] := 5 * points[i]
320          *    ...
321          */
322         for (i = 0; i < totalnum; i++)
323                 {
324                 if (i < num)
325                         {
326                         if (!EC_POINT_copy(val_sub[i][0], points[i])) goto err;
327                         }
328                 else
329                         {
330                         if (!EC_POINT_copy(val_sub[i][0], generator)) goto err;
331                         }
332
333                 if (wsize[i] > 1)
334                         {
335                         if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx)) goto err;
336                         for (j = 1; j < (1u << (wsize[i] - 1)); j++)
337                                 {
338                                 if (!EC_POINT_add(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx)) goto err;
339                                 }
340                         }
341
342                 wNAF[i + 1] = NULL; /* make sure we always have a pivot */
343                 wNAF[i] = compute_wNAF((i < num ? scalars[i] : scalar), wsize[i], &wNAF_len[i]);
344                 if (wNAF[i] == NULL) goto err;
345                 if (wNAF_len[i] > max_len)
346                         max_len = wNAF_len[i];
347                 }
348
349 #if 1 /* optional; EC_window_bits_for_scalar_size assumes we do this step */
350         if (!EC_POINTs_make_affine(group, num_val, val, ctx)) goto err;
351 #endif
352
353         r_is_at_infinity = 1;
354
355         for (k = max_len - 1; k >= 0; k--)
356                 {
357                 if (!r_is_at_infinity)
358                         {
359                         if (!EC_POINT_dbl(group, r, r, ctx)) goto err;
360                         }
361                 
362                 for (i = 0; i < totalnum; i++)
363                         {
364                         if (wNAF_len[i] > (size_t)k)
365                                 {
366                                 int digit = wNAF[i][k];
367                                 int is_neg;
368
369                                 if (digit) 
370                                         {
371                                         is_neg = digit < 0;
372
373                                         if (is_neg)
374                                                 digit = -digit;
375
376                                         if (is_neg != r_is_inverted)
377                                                 {
378                                                 if (!r_is_at_infinity)
379                                                         {
380                                                         if (!EC_POINT_invert(group, r, ctx)) goto err;
381                                                         }
382                                                 r_is_inverted = !r_is_inverted;
383                                                 }
384
385                                         /* digit > 0 */
386
387                                         if (r_is_at_infinity)
388                                                 {
389                                                 if (!EC_POINT_copy(r, val_sub[i][digit >> 1])) goto err;
390                                                 r_is_at_infinity = 0;
391                                                 }
392                                         else
393                                                 {
394                                                 if (!EC_POINT_add(group, r, r, val_sub[i][digit >> 1], ctx)) goto err;
395                                                 }
396                                         }
397                                 }
398                         }
399                 }
400
401         if (r_is_at_infinity)
402                 {
403                 if (!EC_POINT_set_to_infinity(group, r)) goto err;
404                 }
405         else
406                 {
407                 if (r_is_inverted)
408                         if (!EC_POINT_invert(group, r, ctx)) goto err;
409                 }
410         
411         ret = 1;
412
413  err:
414         if (new_ctx != NULL)
415                 BN_CTX_free(new_ctx);
416         if (tmp != NULL)
417                 EC_POINT_free(tmp);
418         if (wsize != NULL)
419                 OPENSSL_free(wsize);
420         if (wNAF_len != NULL)
421                 OPENSSL_free(wNAF_len);
422         if (wNAF != NULL)
423                 {
424                 signed char **w;
425                 
426                 for (w = wNAF; *w != NULL; w++)
427                         OPENSSL_free(*w);
428                 
429                 OPENSSL_free(wNAF);
430                 }
431         if (val != NULL)
432                 {
433                 for (v = val; *v != NULL; v++)
434                         EC_POINT_clear_free(*v);
435
436                 OPENSSL_free(val);
437                 }
438         if (val_sub != NULL)
439                 {
440                 OPENSSL_free(val_sub);
441                 }
442         return ret;
443         }
444
445
446 /* Generic multiplication method.
447  * If group->meth does not provide a multiplication method, default to ec_wNAF_mul;
448  * otherwise use the group->meth's multiplication.
449  */
450 int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
451         size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx)
452         {
453         if (group->meth->mul == 0)
454                 return ec_wNAF_mul(group, r, scalar, num, points, scalars, ctx);
455         else
456                 return group->meth->mul(group, r, scalar, num, points, scalars, ctx);
457         }
458
459
460 int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar, const EC_POINT *point, const BIGNUM *p_scalar, BN_CTX *ctx)
461         {
462         const EC_POINT *points[1];
463         const BIGNUM *scalars[1];
464
465         points[0] = point;
466         scalars[0] = p_scalar;
467
468         return EC_POINTs_mul(group, r, g_scalar, (point != NULL && p_scalar != NULL), points, scalars, ctx);
469         }
470
471
472 int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
473         {
474         const EC_POINT *generator;
475         BN_CTX *new_ctx = NULL;
476         BIGNUM *order;
477         int ret = 0;
478
479         generator = EC_GROUP_get0_generator(group);
480         if (generator == NULL)
481                 {
482                 ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
483                 return 0;
484                 }
485
486         if (ctx == NULL)
487                 {
488                 ctx = new_ctx = BN_CTX_new();
489                 if (ctx == NULL)
490                         return 0;
491                 }
492         
493         BN_CTX_start(ctx);
494         order = BN_CTX_get(ctx);
495         if (order == NULL) goto err;
496         
497         if (!EC_GROUP_get_order(group, order, ctx)) return 0;
498         if (BN_is_zero(order))
499                 {
500                 ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
501                 goto err;
502                 }
503
504         /* TODO */
505
506         ret = 1;
507         
508  err:
509         BN_CTX_end(ctx);
510         if (new_ctx != NULL)
511                 BN_CTX_free(new_ctx);
512         return ret;
513         }
514
515
516 /* Generic multiplicaiton precomputation method.
517  * If group->meth does not provide a multiplication method, default to ec_wNAF_mul and do its
518  * precomputation; otherwise use the group->meth's precomputation if it exists.
519  */
520 int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
521         {
522         if (group->meth->mul == 0)
523                 return ec_wNAF_precompute_mult(group, ctx);
524         else if (group->meth->precompute_mult != 0)
525                 return group->meth->precompute_mult(group, ctx);
526         else
527                 return 1;
528         }