xref: /openbsd-src/lib/libcrypto/ec/ec_mult.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
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: optional precomputation of multiples of the generator */
62 
63 
64 
65 /*
66  * wNAF-based interleaving multi-exponentation method
67  * (<URL:http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp>)
68  */
69 
70 
71 /* Determine the width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'.
72  * This is an array  r[]  of values that are either zero or odd with an
73  * absolute value less than  2^w  satisfying
74  *     scalar = \sum_j r[j]*2^j
75  * where at most one of any  w+1  consecutive digits is non-zero.
76  */
77 static signed char *compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len, BN_CTX *ctx)
78 	{
79 	BIGNUM *c;
80 	int ok = 0;
81 	signed char *r = NULL;
82 	int sign = 1;
83 	int bit, next_bit, mask;
84 	size_t len = 0, j;
85 
86 	BN_CTX_start(ctx);
87 	c = BN_CTX_get(ctx);
88 	if (c == NULL) goto err;
89 
90 	if (w <= 0 || w > 7) /* 'signed char' can represent integers with absolute values less than 2^7 */
91 		{
92 		ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
93 		goto err;
94 		}
95 	bit = 1 << w; /* at most 128 */
96 	next_bit = bit << 1; /* at most 256 */
97 	mask = next_bit - 1; /* at most 255 */
98 
99 	if (!BN_copy(c, scalar)) goto err;
100 	if (c->neg)
101 		{
102 		sign = -1;
103 		c->neg = 0;
104 		}
105 
106 	len = BN_num_bits(c) + 1; /* wNAF may be one digit longer than binary representation */
107 	r = OPENSSL_malloc(len);
108 	if (r == NULL) goto err;
109 
110 	j = 0;
111 	while (!BN_is_zero(c))
112 		{
113 		int u = 0;
114 
115 		if (BN_is_odd(c))
116 			{
117 			if (c->d == NULL || c->top == 0)
118 				{
119 				ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
120 				goto err;
121 				}
122 			u = c->d[0] & mask;
123 			if (u & bit)
124 				{
125 				u -= next_bit;
126 				/* u < 0 */
127 				if (!BN_add_word(c, -u)) goto err;
128 				}
129 			else
130 				{
131 				/* u > 0 */
132 				if (!BN_sub_word(c, u)) goto err;
133 				}
134 
135 			if (u <= -bit || u >= bit || !(u & 1) || c->neg)
136 				{
137 				ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
138 				goto err;
139 				}
140 			}
141 
142 		r[j++] = sign * u;
143 
144 		if (BN_is_odd(c))
145 			{
146 			ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
147 			goto err;
148 			}
149 		if (!BN_rshift1(c, c)) goto err;
150 		}
151 
152 	if (j > len)
153 		{
154 		ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
155 		goto err;
156 		}
157 	len = j;
158 	ok = 1;
159 
160  err:
161 	BN_CTX_end(ctx);
162 	if (!ok)
163 		{
164 		OPENSSL_free(r);
165 		r = NULL;
166 		}
167 	if (ok)
168 		*ret_len = len;
169 	return r;
170 	}
171 
172 
173 /* TODO: table should be optimised for the wNAF-based implementation,
174  *       sometimes smaller windows will give better performance
175  *       (thus the boundaries should be increased)
176  */
177 #define EC_window_bits_for_scalar_size(b) \
178 		((b) >= 2000 ? 6 : \
179 		 (b) >=  800 ? 5 : \
180 		 (b) >=  300 ? 4 : \
181 		 (b) >=   70 ? 3 : \
182 		 (b) >=   20 ? 2 : \
183 		  1)
184 
185 /* Compute
186  *      \sum scalars[i]*points[i],
187  * also including
188  *      scalar*generator
189  * in the addition if scalar != NULL
190  */
191 int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
192 	size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx)
193 	{
194 	BN_CTX *new_ctx = NULL;
195 	EC_POINT *generator = NULL;
196 	EC_POINT *tmp = NULL;
197 	size_t totalnum;
198 	size_t i, j;
199 	int k;
200 	int r_is_inverted = 0;
201 	int r_is_at_infinity = 1;
202 	size_t *wsize = NULL; /* individual window sizes */
203 	signed char **wNAF = NULL; /* individual wNAFs */
204 	size_t *wNAF_len = NULL;
205 	size_t max_len = 0;
206 	size_t num_val;
207 	EC_POINT **val = NULL; /* precomputation */
208 	EC_POINT **v;
209 	EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' */
210 	int ret = 0;
211 
212 	if (group->meth != r->meth)
213 		{
214 		ECerr(EC_F_EC_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
215 		return 0;
216 		}
217 
218 	if ((scalar == NULL) && (num == 0))
219 		{
220 		return EC_POINT_set_to_infinity(group, r);
221 		}
222 
223 	if (scalar != NULL)
224 		{
225 		generator = EC_GROUP_get0_generator(group);
226 		if (generator == NULL)
227 			{
228 			ECerr(EC_F_EC_POINTS_MUL, EC_R_UNDEFINED_GENERATOR);
229 			return 0;
230 			}
231 		}
232 
233 	for (i = 0; i < num; i++)
234 		{
235 		if (group->meth != points[i]->meth)
236 			{
237 			ECerr(EC_F_EC_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
238 			return 0;
239 			}
240 		}
241 
242 	totalnum = num + (scalar != NULL);
243 
244 	wsize = OPENSSL_malloc(totalnum * sizeof wsize[0]);
245 	wNAF_len = OPENSSL_malloc(totalnum * sizeof wNAF_len[0]);
246 	wNAF = OPENSSL_malloc((totalnum + 1) * sizeof wNAF[0]);
247 	if (wNAF != NULL)
248 		{
249 		wNAF[0] = NULL; /* preliminary pivot */
250 		}
251 	if (wsize == NULL || wNAF_len == NULL || wNAF == NULL) goto err;
252 
253 	/* num_val := total number of points to precompute */
254 	num_val = 0;
255 	for (i = 0; i < totalnum; i++)
256 		{
257 		size_t bits;
258 
259 		bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
260 		wsize[i] = EC_window_bits_for_scalar_size(bits);
261 		num_val += 1u << (wsize[i] - 1);
262 		}
263 
264 	/* all precomputed points go into a single array 'val',
265 	 * 'val_sub[i]' is a pointer to the subarray for the i-th point */
266 	val = OPENSSL_malloc((num_val + 1) * sizeof val[0]);
267 	if (val == NULL) goto err;
268 	val[num_val] = NULL; /* pivot element */
269 
270 	val_sub = OPENSSL_malloc(totalnum * sizeof val_sub[0]);
271 	if (val_sub == NULL) goto err;
272 
273 	/* allocate points for precomputation */
274 	v = val;
275 	for (i = 0; i < totalnum; i++)
276 		{
277 		val_sub[i] = v;
278 		for (j = 0; j < (1u << (wsize[i] - 1)); j++)
279 			{
280 			*v = EC_POINT_new(group);
281 			if (*v == NULL) goto err;
282 			v++;
283 			}
284 		}
285 	if (!(v == val + num_val))
286 		{
287 		ECerr(EC_F_EC_POINTS_MUL, ERR_R_INTERNAL_ERROR);
288 		goto err;
289 		}
290 
291 	if (ctx == NULL)
292 		{
293 		ctx = new_ctx = BN_CTX_new();
294 		if (ctx == NULL)
295 			goto err;
296 		}
297 
298 	tmp = EC_POINT_new(group);
299 	if (tmp == NULL) goto err;
300 
301 	/* prepare precomputed values:
302 	 *    val_sub[i][0] :=     points[i]
303 	 *    val_sub[i][1] := 3 * points[i]
304 	 *    val_sub[i][2] := 5 * points[i]
305 	 *    ...
306 	 */
307 	for (i = 0; i < totalnum; i++)
308 		{
309 		if (i < num)
310 			{
311 			if (!EC_POINT_copy(val_sub[i][0], points[i])) goto err;
312 			}
313 		else
314 			{
315 			if (!EC_POINT_copy(val_sub[i][0], generator)) goto err;
316 			}
317 
318 		if (wsize[i] > 1)
319 			{
320 			if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx)) goto err;
321 			for (j = 1; j < (1u << (wsize[i] - 1)); j++)
322 				{
323 				if (!EC_POINT_add(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx)) goto err;
324 				}
325 			}
326 
327 		wNAF[i + 1] = NULL; /* make sure we always have a pivot */
328 		wNAF[i] = compute_wNAF((i < num ? scalars[i] : scalar), wsize[i], &wNAF_len[i], ctx);
329 		if (wNAF[i] == NULL) goto err;
330 		if (wNAF_len[i] > max_len)
331 			max_len = wNAF_len[i];
332 		}
333 
334 #if 1 /* optional; EC_window_bits_for_scalar_size assumes we do this step */
335 	if (!EC_POINTs_make_affine(group, num_val, val, ctx)) goto err;
336 #endif
337 
338 	r_is_at_infinity = 1;
339 
340 	for (k = max_len - 1; k >= 0; k--)
341 		{
342 		if (!r_is_at_infinity)
343 			{
344 			if (!EC_POINT_dbl(group, r, r, ctx)) goto err;
345 			}
346 
347 		for (i = 0; i < totalnum; i++)
348 			{
349 			if (wNAF_len[i] > (size_t)k)
350 				{
351 				int digit = wNAF[i][k];
352 				int is_neg;
353 
354 				if (digit)
355 					{
356 					is_neg = digit < 0;
357 
358 					if (is_neg)
359 						digit = -digit;
360 
361 					if (is_neg != r_is_inverted)
362 						{
363 						if (!r_is_at_infinity)
364 							{
365 							if (!EC_POINT_invert(group, r, ctx)) goto err;
366 							}
367 						r_is_inverted = !r_is_inverted;
368 						}
369 
370 					/* digit > 0 */
371 
372 					if (r_is_at_infinity)
373 						{
374 						if (!EC_POINT_copy(r, val_sub[i][digit >> 1])) goto err;
375 						r_is_at_infinity = 0;
376 						}
377 					else
378 						{
379 						if (!EC_POINT_add(group, r, r, val_sub[i][digit >> 1], ctx)) goto err;
380 						}
381 					}
382 				}
383 			}
384 		}
385 
386 	if (r_is_at_infinity)
387 		{
388 		if (!EC_POINT_set_to_infinity(group, r)) goto err;
389 		}
390 	else
391 		{
392 		if (r_is_inverted)
393 			if (!EC_POINT_invert(group, r, ctx)) goto err;
394 		}
395 
396 	ret = 1;
397 
398  err:
399 	if (new_ctx != NULL)
400 		BN_CTX_free(new_ctx);
401 	if (tmp != NULL)
402 		EC_POINT_free(tmp);
403 	if (wsize != NULL)
404 		OPENSSL_free(wsize);
405 	if (wNAF_len != NULL)
406 		OPENSSL_free(wNAF_len);
407 	if (wNAF != NULL)
408 		{
409 		signed char **w;
410 
411 		for (w = wNAF; *w != NULL; w++)
412 			OPENSSL_free(*w);
413 
414 		OPENSSL_free(wNAF);
415 		}
416 	if (val != NULL)
417 		{
418 		for (v = val; *v != NULL; v++)
419 			EC_POINT_clear_free(*v);
420 
421 		OPENSSL_free(val);
422 		}
423 	if (val_sub != NULL)
424 		{
425 		OPENSSL_free(val_sub);
426 		}
427 	return ret;
428 	}
429 
430 
431 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)
432 	{
433 	const EC_POINT *points[1];
434 	const BIGNUM *scalars[1];
435 
436 	points[0] = point;
437 	scalars[0] = p_scalar;
438 
439 	return EC_POINTs_mul(group, r, g_scalar, (point != NULL && p_scalar != NULL), points, scalars, ctx);
440 	}
441 
442 
443 int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
444 	{
445 	const EC_POINT *generator;
446 	BN_CTX *new_ctx = NULL;
447 	BIGNUM *order;
448 	int ret = 0;
449 
450 	generator = EC_GROUP_get0_generator(group);
451 	if (generator == NULL)
452 		{
453 		ECerr(EC_F_EC_GROUP_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
454 		return 0;
455 		}
456 
457 	if (ctx == NULL)
458 		{
459 		ctx = new_ctx = BN_CTX_new();
460 		if (ctx == NULL)
461 			return 0;
462 		}
463 
464 	BN_CTX_start(ctx);
465 	order = BN_CTX_get(ctx);
466 	if (order == NULL) goto err;
467 
468 	if (!EC_GROUP_get_order(group, order, ctx)) return 0;
469 	if (BN_is_zero(order))
470 		{
471 		ECerr(EC_F_EC_GROUP_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
472 		goto err;
473 		}
474 
475 	/* TODO */
476 
477 	ret = 1;
478 
479  err:
480 	BN_CTX_end(ctx);
481 	if (new_ctx != NULL)
482 		BN_CTX_free(new_ctx);
483 	return ret;
484 	}
485