d1478740a38af96387e78c499014c63d857ad703
[openssl.git] / crypto / ec / ec_mult.c
1 /* crypto/ec/ec_mult.c */
2 /* ====================================================================
3  * Copyright (c) 1998-2001 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 #include <openssl/err.h>
57
58 #include "ec_lcl.h"
59
60
61 /* TODO: width-m NAFs */
62
63 /* TODO: optional Lim-Lee precomputation for the generator */
64
65
66 #define EC_window_bits_for_scalar_size(b) \
67                 ((b) >= 1500 ? 6 : \
68                  (b) >=  550 ? 5 : \
69                  (b) >=  200 ? 4 : \
70                  (b) >=   55 ? 3 : \
71                  (b) >=   20 ? 2 : \
72                   1)
73 /* For window size 'w' (w >= 2), we compute the odd multiples
74  *      1*P .. (2^w-1)*P.
75  * This accounts for  2^(w-1)  point additions (neglecting constants),
76  * each of which requires 16 field multiplications (4 squarings
77  * and 12 general multiplications) in the case of curves defined
78  * over GF(p), which are the only curves we have so far.
79  *
80  * Converting these precomputed points into affine form takes
81  * three field multiplications for inverting Z and one squaring
82  * and three multiplications for adjusting X and Y, i.e.
83  * 7 multiplications in total (1 squaring and 6 general multiplications),
84  * again except for constants.
85  *
86  * The average number of windows for a 'b' bit scalar is roughly
87  *          b/(w+1).
88  * Each of these windows (except possibly for the first one, but
89  * we are ignoring constants anyway) requires one point addition.
90  * As the precomputed table stores points in affine form, these
91  * additions take only 11 field multiplications each (3 squarings
92  * and 8 general multiplications).
93  *
94  * So the total workload, except for constants, is
95  *
96  *        2^(w-1)*[5 squarings + 18 multiplications]
97  *      + (b/(w+1))*[3 squarings + 8 multiplications]
98  *
99  * If we assume that 10 squarings are as costly as 9 multiplications,
100  * our task is to find the 'w' that, given 'b', minimizes
101  *
102  *        2^(w-1)*(5*9 + 18*10) + (b/(w+1))*(3*9 + 8*10)
103  *      = 2^(w-1)*225 +           (b/(w+1))*107.
104  *
105  * Thus optimal window sizes should be roughly as follows:
106  *
107  *    w >= 6  if         b >= 1414
108  *     w = 5  if 1413 >= b >=  505
109  *     w = 4  if  504 >= b >=  169
110  *     w = 3  if  168 >= b >=   51
111  *     w = 2  if   50 >= b >=   13
112  *     w = 1  if   12 >= b
113  *
114  * If we assume instead that squarings are exactly as costly as
115  * multiplications, we have to minimize
116  *      2^(w-1)*23 + (b/(w+1))*11.
117  *
118  * This gives us the following (nearly unchanged) table of optimal
119  * windows sizes:
120  *
121  *    w >= 6  if         b >= 1406
122  *     w = 5  if 1405 >= b >=  502
123  *     w = 4  if  501 >= b >=  168
124  *     w = 3  if  167 >= b >=   51
125  *     w = 2  if   50 >= b >=   13
126  *     w = 1  if   12 >= b
127  *
128  * Note that neither table tries to take into account memory usage
129  * (code locality etc.).  Actual timings with NIST curve P-192 and
130  * 192-bit scalars show that  w = 3  (instead of 4) is preferrable;
131  * and timings with NIST curve P-521 and 521-bit scalars show that
132  * w = 4  (instead of 5) is preferrable.  So we round up all the
133  * boundaries and use the following table:
134  *
135  *    w >= 6  if         b >= 1500
136  *     w = 5  if 1499 >= b >=  550
137  *     w = 4  if  549 >= b >=  200
138  *     w = 3  if  199 >= b >=   55
139  *     w = 2  if   54 >= b >=   20
140  *     w = 1  if   19 >= b
141  */
142
143
144
145 /* Compute
146  *      \sum scalars[i]*points[i]
147  * where
148  *      scalar*generator
149  * is included in the addition if scalar != NULL
150  */
151 int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
152         size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx)
153         {
154         BN_CTX *new_ctx = NULL;
155         EC_POINT *generator = NULL;
156         EC_POINT *tmp = NULL;
157         size_t totalnum;
158         size_t i, j;
159         int k, t;
160         int r_is_at_infinity = 1;
161         size_t max_bits = 0;
162         size_t *wsize = NULL; /* individual window sizes */
163         unsigned long *wbits = NULL; /* individual window contents */
164         int *wpos = NULL; /* position of bottom bit of current individual windows
165                            * (wpos[i] is valid if wbits[i] != 0) */
166         size_t num_val;
167         EC_POINT **val = NULL; /* precomputation */
168         EC_POINT **v;
169         EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' */
170         int ret = 0;
171         
172         if (scalar != NULL)
173                 {
174                 generator = EC_GROUP_get0_generator(group);
175                 if (generator == NULL)
176                         {
177                         ECerr(EC_F_EC_POINTS_MUL, EC_R_UNDEFINED_GENERATOR);
178                         return 0;
179                         }
180                 }
181         
182         for (i = 0; i < num; i++)
183                 {
184                 if (group->meth != points[i]->meth)
185                         {
186                         ECerr(EC_F_EC_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
187                         return 0;
188                         }
189                 }
190
191         totalnum = num + (scalar != NULL);
192
193         wsize = OPENSSL_malloc(totalnum * sizeof wsize[0]);
194         wbits = OPENSSL_malloc(totalnum * sizeof wbits[0]);
195         wpos = OPENSSL_malloc(totalnum * sizeof wpos[0]);
196         if (wsize == NULL || wbits == NULL || wpos == NULL) goto err;
197
198         /* num_val := total number of points to precompute */
199         num_val = 0;
200         for (i = 0; i < totalnum; i++)
201                 {
202                 size_t bits;
203
204                 bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
205                 wsize[i] = EC_window_bits_for_scalar_size(bits);
206                 num_val += 1 << (wsize[i] - 1);
207                 if (bits > max_bits)
208                         max_bits = bits;
209                 wbits[i] = 0;
210                 wpos[i] = 0;
211                 }
212
213         /* all precomputed points go into a single array 'val',
214          * 'val_sub[i]' is a pointer to the subarray for the i-th point */
215         val = OPENSSL_malloc((num_val + 1) * sizeof val[0]);
216         if (val == NULL) goto err;
217         val[num_val] = NULL; /* pivot element */
218
219         val_sub = OPENSSL_malloc(totalnum * sizeof val_sub[0]);
220         if (val_sub == NULL) goto err;
221
222         /* allocate points for precomputation */
223         v = val;
224         for (i = 0; i < totalnum; i++)
225                 {
226                 val_sub[i] = v;
227                 for (j = 0; j < (1 << (wsize[i] - 1)); j++)
228                         {
229                         *v = EC_POINT_new(group);
230                         if (*v == NULL) goto err;
231                         v++;
232                         }
233                 }
234         if (!(v == val + num_val))
235                 {
236                 ECerr(EC_F_EC_POINTS_MUL, ERR_R_INTERNAL_ERROR);
237                 goto err;
238                 }
239
240         if (ctx == NULL)
241                 {
242                 ctx = new_ctx = BN_CTX_new();
243                 if (ctx == NULL)
244                         goto err;
245                 }
246         
247         tmp = EC_POINT_new(group);
248         if (tmp == NULL) goto err;
249
250         /* prepare precomputed values:
251          *    val_sub[i][0] :=     points[i]
252          *    val_sub[i][1] := 3 * points[i]
253          *    val_sub[i][2] := 5 * points[i]
254          *    ...
255          */
256         for (i = 0; i < totalnum; i++)
257                 {
258                 if (i < num)
259                         {
260                         if (!EC_POINT_copy(val_sub[i][0], points[i])) goto err;
261                         if (scalars[i]->neg)
262                                 {
263                                 if (!EC_POINT_invert(group, val_sub[i][0], ctx)) goto err;
264                                 }
265                         }
266                 else
267                         {
268                         if (!EC_POINT_copy(val_sub[i][0], generator)) goto err;
269                         if (scalar->neg)
270                                 {
271                                 if (!EC_POINT_invert(group, val_sub[i][0], ctx)) goto err;
272                                 }
273                         }
274
275                 if (wsize[i] > 1)
276                         {
277                         if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx)) goto err;
278                         for (j = 1; j < (1 << (wsize[i] - 1)); j++)
279                                 {
280                                 if (!EC_POINT_add(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx)) goto err;
281                                 }
282                         }
283                 }
284
285 #if 1 /* optional, maybe we should only do this if total_num > 1 */
286         if (!EC_POINTs_make_affine(group, num_val, val, ctx)) goto err;
287 #endif
288
289         r_is_at_infinity = 1;
290
291         for (k = max_bits - 1; k >= 0; k--)
292                 {
293                 if (!r_is_at_infinity)
294                         {
295                         if (!EC_POINT_dbl(group, r, r, ctx)) goto err;
296                         }
297                 
298                 for (i = 0; i < totalnum; i++)
299                         {
300                         if (wbits[i] == 0)
301                                 {
302                                 const BIGNUM *s;
303
304                                 s = i < num ? scalars[i] : scalar;
305
306                                 if (BN_is_bit_set(s, k))
307                                         {
308                                         /* look at bits  k - wsize[i] + 1 .. k  for this window */
309                                         t = k - wsize[i] + 1;
310                                         while (!BN_is_bit_set(s, t)) /* BN_is_bit_set is false for t < 0 */
311                                                 t++;
312                                         wpos[i] = t;
313                                         wbits[i] = 1;
314                                         for (t = k - 1; t >= wpos[i]; t--)
315                                                 {
316                                                 wbits[i] <<= 1;
317                                                 if (BN_is_bit_set(s, t))
318                                                         wbits[i]++;
319                                                 }
320                                         /* now wbits[i] is the odd bit pattern at bits wpos[i] .. k */
321                                         }
322                                 }
323                         
324                         if ((wbits[i] != 0) && (wpos[i] == k))
325                                 {
326                                 if (r_is_at_infinity)
327                                         {
328                                         if (!EC_POINT_copy(r, val_sub[i][wbits[i] >> 1])) goto err;
329                                         r_is_at_infinity = 0;
330                                         }
331                                 else
332                                         {
333                                         if (!EC_POINT_add(group, r, r, val_sub[i][wbits[i] >> 1], ctx)) goto err;
334                                         }
335                                 wbits[i] = 0;
336                                 }
337                         }
338                 }
339
340         if (r_is_at_infinity)
341                 if (!EC_POINT_set_to_infinity(group, r)) goto err;
342         
343         ret = 1;
344
345  err:
346         if (new_ctx != NULL)
347                 BN_CTX_free(new_ctx);
348         if (tmp != NULL)
349                 EC_POINT_free(tmp);
350         if (wsize != NULL)
351                 OPENSSL_free(wsize);
352         if (wbits != NULL)
353                 OPENSSL_free(wbits);
354         if (wpos != NULL)
355                 OPENSSL_free(wpos);
356         if (val != NULL)
357                 {
358                 for (v = val; *v != NULL; v++)
359                         EC_POINT_clear_free(*v);
360
361                 OPENSSL_free(val);
362                 }
363         if (val_sub != NULL)
364                 {
365                 OPENSSL_free(val_sub);
366                 }
367         return ret;
368         }
369
370
371 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)
372         {
373         const EC_POINT *points[1];
374         const BIGNUM *scalars[1];
375
376         points[0] = point;
377         scalars[0] = p_scalar;
378
379         return EC_POINTs_mul(group, r, g_scalar, (point != NULL && p_scalar != NULL), points, scalars, ctx);
380         }
381
382
383 int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
384         {
385         const EC_POINT *generator;
386         BN_CTX *new_ctx = NULL;
387         BIGNUM *order;
388         int ret = 0;
389
390         generator = EC_GROUP_get0_generator(group);
391         if (generator == NULL)
392                 {
393                 ECerr(EC_F_EC_GROUP_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
394                 return 0;
395                 }
396
397         if (ctx == NULL)
398                 {
399                 ctx = new_ctx = BN_CTX_new();
400                 if (ctx == NULL)
401                         return 0;
402                 }
403         
404         BN_CTX_start(ctx);
405         order = BN_CTX_get(ctx);
406         if (order == NULL) goto err;
407         
408         if (!EC_GROUP_get_order(group, order, ctx)) return 0;
409         if (BN_is_zero(order))
410                 {
411                 ECerr(EC_F_EC_GROUP_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
412                 goto err;
413                 }
414
415         /* TODO */
416
417         ret = 1;
418         
419  err:
420         BN_CTX_end(ctx);
421         if (new_ctx != NULL)
422                 BN_CTX_free(new_ctx);
423         return ret;
424         }