1 /* Originally written by Bodo Moeller for the OpenSSL project.
2  * ====================================================================
3  * Copyright (c) 1998-2005 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  *
58  * Portions of the attached software ("Contribution") are developed by
59  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
60  *
61  * The Contribution is licensed pursuant to the OpenSSL open source
62  * license provided above.
63  *
64  * The elliptic curve binary polynomial software is originally written by
65  * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems
66  * Laboratories. */
67 
68 #ifndef OPENSSL_HEADER_EC_INTERNAL_H
69 #define OPENSSL_HEADER_EC_INTERNAL_H
70 
71 #include <openssl/base.h>
72 
73 #include <openssl/bn.h>
74 #include <openssl/ec.h>
75 #include <openssl/ex_data.h>
76 #include <openssl/type_check.h>
77 
78 #include "../bn/internal.h"
79 
80 #if defined(__cplusplus)
81 extern "C" {
82 #endif
83 
84 
85 // EC internals.
86 
87 
88 // Cap the size of all field elements and scalars, including custom curves, to
89 // 66 bytes, large enough to fit secp521r1 and brainpoolP512r1, which appear to
90 // be the largest fields anyone plausibly uses.
91 #define EC_MAX_BYTES 66
92 #define EC_MAX_WORDS ((EC_MAX_BYTES + BN_BYTES - 1) / BN_BYTES)
93 
94 OPENSSL_STATIC_ASSERT(EC_MAX_WORDS <= BN_SMALL_MAX_WORDS,
95                       "bn_*_small functions not usable");
96 
97 
98 // Scalars.
99 
100 // An EC_SCALAR is an integer fully reduced modulo the order. Only the first
101 // |order->width| words are used. An |EC_SCALAR| is specific to an |EC_GROUP|
102 // and must not be mixed between groups.
103 typedef union {
104   // bytes is the representation of the scalar in little-endian order.
105   uint8_t bytes[EC_MAX_BYTES];
106   BN_ULONG words[EC_MAX_WORDS];
107 } EC_SCALAR;
108 
109 // ec_bignum_to_scalar converts |in| to an |EC_SCALAR| and writes it to
110 // |*out|. It returns one on success and zero if |in| is out of range.
111 OPENSSL_EXPORT int ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out,
112                                        const BIGNUM *in);
113 
114 // ec_scalar_to_bytes serializes |in| as a big-endian bytestring to |out| and
115 // sets |*out_len| to the number of bytes written. The number of bytes written
116 // is |BN_num_bytes(&group->order)|, which is at most |EC_MAX_BYTES|.
117 OPENSSL_EXPORT void ec_scalar_to_bytes(const EC_GROUP *group, uint8_t *out,
118                                        size_t *out_len, const EC_SCALAR *in);
119 
120 // ec_scalar_from_bytes deserializes |in| and stores the resulting scalar over
121 // group |group| to |out|. It returns one on success and zero if |in| is
122 // invalid.
123 int ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out,
124                          const uint8_t *in, size_t len);
125 
126 // ec_scalar_reduce sets |out| to |words|, reduced modulo the group order.
127 // |words| must be less than order^2. |num| must be at most twice the width of
128 // group order. This function treats |words| as secret.
129 void ec_scalar_reduce(const EC_GROUP *group, EC_SCALAR *out,
130                       const BN_ULONG *words, size_t num);
131 
132 // ec_random_nonzero_scalar sets |out| to a uniformly selected random value from
133 // 1 to |group->order| - 1. It returns one on success and zero on error.
134 int ec_random_nonzero_scalar(const EC_GROUP *group, EC_SCALAR *out,
135                              const uint8_t additional_data[32]);
136 
137 // ec_scalar_equal_vartime returns one if |a| and |b| are equal and zero
138 // otherwise. Both values are treated as public.
139 int ec_scalar_equal_vartime(const EC_GROUP *group, const EC_SCALAR *a,
140                             const EC_SCALAR *b);
141 
142 // ec_scalar_is_zero returns one if |a| is zero and zero otherwise.
143 int ec_scalar_is_zero(const EC_GROUP *group, const EC_SCALAR *a);
144 
145 // ec_scalar_add sets |r| to |a| + |b|.
146 void ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
147                    const EC_SCALAR *b);
148 
149 // ec_scalar_sub sets |r| to |a| - |b|.
150 void ec_scalar_sub(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
151                    const EC_SCALAR *b);
152 
153 // ec_scalar_neg sets |r| to -|a|.
154 void ec_scalar_neg(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a);
155 
156 // ec_scalar_to_montgomery sets |r| to |a| in Montgomery form.
157 void ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r,
158                              const EC_SCALAR *a);
159 
160 // ec_scalar_to_montgomery sets |r| to |a| converted from Montgomery form.
161 void ec_scalar_from_montgomery(const EC_GROUP *group, EC_SCALAR *r,
162                                const EC_SCALAR *a);
163 
164 // ec_scalar_mul_montgomery sets |r| to |a| * |b| where inputs and outputs are
165 // in Montgomery form.
166 void ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r,
167                               const EC_SCALAR *a, const EC_SCALAR *b);
168 
169 // ec_scalar_inv0_montgomery sets |r| to |a|^-1 where inputs and outputs are in
170 // Montgomery form. If |a| is zero, |r| is set to zero.
171 void ec_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r,
172                                const EC_SCALAR *a);
173 
174 // ec_scalar_to_montgomery_inv_vartime sets |r| to |a|^-1 R. That is, it takes
175 // in |a| not in Montgomery form and computes the inverse in Montgomery form. It
176 // returns one on success and zero if |a| has no inverse. This function assumes
177 // |a| is public and may leak information about it via timing.
178 //
179 // Note this is not the same operation as |ec_scalar_inv0_montgomery|.
180 int ec_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, EC_SCALAR *r,
181                                         const EC_SCALAR *a);
182 
183 // ec_scalar_select, in constant time, sets |out| to |a| if |mask| is all ones
184 // and |b| if |mask| is all zeros.
185 void ec_scalar_select(const EC_GROUP *group, EC_SCALAR *out, BN_ULONG mask,
186                       const EC_SCALAR *a, const EC_SCALAR *b);
187 
188 
189 // Field elements.
190 
191 // An EC_FELEM represents a field element. Only the first |field->width| words
192 // are used. An |EC_FELEM| is specific to an |EC_GROUP| and must not be mixed
193 // between groups. Additionally, the representation (whether or not elements are
194 // represented in Montgomery-form) may vary between |EC_METHOD|s.
195 typedef union {
196   // bytes is the representation of the field element in little-endian order.
197   uint8_t bytes[EC_MAX_BYTES];
198   BN_ULONG words[EC_MAX_WORDS];
199 } EC_FELEM;
200 
201 // ec_bignum_to_felem converts |in| to an |EC_FELEM|. It returns one on success
202 // and zero if |in| is out of range.
203 int ec_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out, const BIGNUM *in);
204 
205 // ec_felem_to_bignum converts |in| to a |BIGNUM|. It returns one on success and
206 // zero on allocation failure.
207 int ec_felem_to_bignum(const EC_GROUP *group, BIGNUM *out, const EC_FELEM *in);
208 
209 // ec_felem_to_bytes serializes |in| as a big-endian bytestring to |out| and
210 // sets |*out_len| to the number of bytes written. The number of bytes written
211 // is |BN_num_bytes(&group->order)|, which is at most |EC_MAX_BYTES|.
212 void ec_felem_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len,
213                        const EC_FELEM *in);
214 
215 // ec_felem_from_bytes deserializes |in| and stores the resulting field element
216 // to |out|. It returns one on success and zero if |in| is invalid.
217 int ec_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, const uint8_t *in,
218                         size_t len);
219 
220 // ec_felem_neg sets |out| to -|a|.
221 void ec_felem_neg(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a);
222 
223 // ec_felem_add sets |out| to |a| + |b|.
224 void ec_felem_add(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
225                   const EC_FELEM *b);
226 
227 // ec_felem_add sets |out| to |a| - |b|.
228 void ec_felem_sub(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
229                   const EC_FELEM *b);
230 
231 // ec_felem_non_zero_mask returns all ones if |a| is non-zero and all zeros
232 // otherwise.
233 BN_ULONG ec_felem_non_zero_mask(const EC_GROUP *group, const EC_FELEM *a);
234 
235 // ec_felem_select, in constant time, sets |out| to |a| if |mask| is all ones
236 // and |b| if |mask| is all zeros.
237 void ec_felem_select(const EC_GROUP *group, EC_FELEM *out, BN_ULONG mask,
238                      const EC_FELEM *a, const EC_FELEM *b);
239 
240 // ec_felem_equal returns one if |a| and |b| are equal and zero otherwise.
241 int ec_felem_equal(const EC_GROUP *group, const EC_FELEM *a, const EC_FELEM *b);
242 
243 
244 // Points.
245 //
246 // Points may represented in affine coordinates as |EC_AFFINE| or Jacobian
247 // coordinates as |EC_RAW_POINT|. Affine coordinates directly represent a
248 // point on the curve, but point addition over affine coordinates requires
249 // costly field inversions, so arithmetic is done in Jacobian coordinates.
250 // Converting from affine to Jacobian is cheap, while converting from Jacobian
251 // to affine costs a field inversion. (Jacobian coordinates amortize the field
252 // inversions needed in a sequence of point operations.)
253 //
254 // TODO(davidben): Rename |EC_RAW_POINT| to |EC_JACOBIAN|.
255 
256 // An EC_RAW_POINT represents an elliptic curve point in Jacobian coordinates.
257 // Unlike |EC_POINT|, it is a plain struct which can be stack-allocated and
258 // needs no cleanup. It is specific to an |EC_GROUP| and must not be mixed
259 // between groups.
260 typedef struct {
261   // X, Y, and Z are Jacobian projective coordinates. They represent
262   // (X/Z^2, Y/Z^3) if Z != 0 and the point at infinity otherwise.
263   EC_FELEM X, Y, Z;
264 } EC_RAW_POINT;
265 
266 // An EC_AFFINE represents an elliptic curve point in affine coordinates.
267 // coordinates. Note the point at infinity cannot be represented in affine
268 // coordinates.
269 typedef struct {
270   EC_FELEM X, Y;
271 } EC_AFFINE;
272 
273 // ec_affine_to_jacobian converts |p| to Jacobian form and writes the result to
274 // |*out|. This operation is very cheap and only costs a few copies.
275 void ec_affine_to_jacobian(const EC_GROUP *group, EC_RAW_POINT *out,
276                            const EC_AFFINE *p);
277 
278 // ec_jacobian_to_affine converts |p| to affine form and writes the result to
279 // |*out|. It returns one on success and zero if |p| was the point at infinity.
280 // This operation performs a field inversion and should only be done once per
281 // point.
282 //
283 // If only extracting the x-coordinate, use |ec_get_x_coordinate_*| which is
284 // slightly faster.
285 int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out,
286                           const EC_RAW_POINT *p);
287 
288 // ec_jacobian_to_affine_batch converts |num| points in |in| from Jacobian
289 // coordinates to affine coordinates and writes the results to |out|. It returns
290 // one on success and zero if any of the input points were infinity.
291 //
292 // This function is not implemented for all curves. Add implementations as
293 // needed.
294 int ec_jacobian_to_affine_batch(const EC_GROUP *group, EC_AFFINE *out,
295                                 const EC_RAW_POINT *in, size_t num);
296 
297 // ec_point_set_affine_coordinates sets |out|'s to a point with affine
298 // coordinates |x| and |y|. It returns one if the point is on the curve and
299 // zero otherwise. If the point is not on the curve, the value of |out| is
300 // undefined.
301 int ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out,
302                                     const EC_FELEM *x, const EC_FELEM *y);
303 
304 // ec_point_mul_scalar sets |r| to |p| * |scalar|. Both inputs are considered
305 // secret.
306 int ec_point_mul_scalar(const EC_GROUP *group, EC_RAW_POINT *r,
307                         const EC_RAW_POINT *p, const EC_SCALAR *scalar);
308 
309 // ec_point_mul_scalar_base sets |r| to generator * |scalar|. |scalar| is
310 // treated as secret.
311 int ec_point_mul_scalar_base(const EC_GROUP *group, EC_RAW_POINT *r,
312                              const EC_SCALAR *scalar);
313 
314 // ec_point_mul_scalar_batch sets |r| to |p0| * |scalar0| + |p1| * |scalar1| +
315 // |p2| * |scalar2|. |p2| may be NULL to skip that term.
316 //
317 // The inputs are treated as secret, however, this function leaks information
318 // about whether intermediate computations add a point to itself. Callers must
319 // ensure that discrete logs between |p0|, |p1|, and |p2| are uniformly
320 // distributed and independent of the scalars, which should be uniformly
321 // selected and not under the attackers control. This ensures the doubling case
322 // will occur with negligible probability.
323 //
324 // This function is not implemented for all curves. Add implementations as
325 // needed.
326 //
327 // TODO(davidben): This function does not use base point tables. For now, it is
328 // only used with the generic |EC_GFp_mont_method| implementation which has
329 // none. If generalizing to tuned curves, this may be useful. However, we still
330 // must double up to the least efficient input, so precomputed tables can only
331 // save table setup and allow a wider window size.
332 int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_RAW_POINT *r,
333                               const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
334                               const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
335                               const EC_RAW_POINT *p2, const EC_SCALAR *scalar2);
336 
337 #define EC_MONT_PRECOMP_COMB_SIZE 5
338 
339 // An |EC_PRECOMP| stores precomputed information about a point, to optimize
340 // repeated multiplications involving it. It is a union so different
341 // |EC_METHOD|s can store different information in it.
342 typedef union {
343   EC_AFFINE comb[(1 << EC_MONT_PRECOMP_COMB_SIZE) - 1];
344 } EC_PRECOMP;
345 
346 // ec_init_precomp precomputes multiples of |p| and writes the result to |out|.
347 // It returns one on success and zero on error. The resulting table may be used
348 // with |ec_point_mul_scalar_precomp|. This function will fail if |p| is the
349 // point at infinity.
350 //
351 // This function is not implemented for all curves. Add implementations as
352 // needed.
353 int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out,
354                     const EC_RAW_POINT *p);
355 
356 // ec_point_mul_scalar_precomp sets |r| to |p0| * |scalar0| + |p1| * |scalar1| +
357 // |p2| * |scalar2|. |p1| or |p2| may be NULL to skip the corresponding term.
358 // The points are represented as |EC_PRECOMP| and must be initialized with
359 // |ec_init_precomp|. This function runs faster than |ec_point_mul_scalar_batch|
360 // but requires setup work per input point, so it is only appropriate for points
361 // which are used frequently.
362 //
363 // The inputs are treated as secret, however, this function leaks information
364 // about whether intermediate computations add a point to itself. Callers must
365 // ensure that discrete logs between |p0|, |p1|, and |p2| are uniformly
366 // distributed and independent of the scalars, which should be uniformly
367 // selected and not under the attackers control. This ensures the doubling case
368 // will occur with negligible probability.
369 //
370 // This function is not implemented for all curves. Add implementations as
371 // needed.
372 //
373 // TODO(davidben): This function does not use base point tables. For now, it is
374 // only used with the generic |EC_GFp_mont_method| implementation which has
375 // none. If generalizing to tuned curves, we should add a parameter for the base
376 // point and arrange for the generic implementation to have base point tables
377 // available.
378 int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_RAW_POINT *r,
379                                 const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
380                                 const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
381                                 const EC_PRECOMP *p2, const EC_SCALAR *scalar2);
382 
383 // ec_point_mul_scalar_public sets |r| to
384 // generator * |g_scalar| + |p| * |p_scalar|. It assumes that the inputs are
385 // public so there is no concern about leaking their values through timing.
386 OPENSSL_EXPORT int ec_point_mul_scalar_public(const EC_GROUP *group,
387                                               EC_RAW_POINT *r,
388                                               const EC_SCALAR *g_scalar,
389                                               const EC_RAW_POINT *p,
390                                               const EC_SCALAR *p_scalar);
391 
392 // ec_point_mul_scalar_public_batch sets |r| to the sum of generator *
393 // |g_scalar| and |points[i]| * |scalars[i]| where |points| and |scalars| have
394 // |num| elements. It assumes that the inputs are public so there is no concern
395 // about leaking their values through timing. |g_scalar| may be NULL to skip
396 // that term.
397 //
398 // This function is not implemented for all curves. Add implementations as
399 // needed.
400 int ec_point_mul_scalar_public_batch(const EC_GROUP *group, EC_RAW_POINT *r,
401                                      const EC_SCALAR *g_scalar,
402                                      const EC_RAW_POINT *points,
403                                      const EC_SCALAR *scalars, size_t num);
404 
405 // ec_point_select, in constant time, sets |out| to |a| if |mask| is all ones
406 // and |b| if |mask| is all zeros.
407 void ec_point_select(const EC_GROUP *group, EC_RAW_POINT *out, BN_ULONG mask,
408                      const EC_RAW_POINT *a, const EC_RAW_POINT *b);
409 
410 // ec_affine_select behaves like |ec_point_select| but acts on affine points.
411 void ec_affine_select(const EC_GROUP *group, EC_AFFINE *out, BN_ULONG mask,
412                       const EC_AFFINE *a, const EC_AFFINE *b);
413 
414 // ec_precomp_select behaves like |ec_point_select| but acts on |EC_PRECOMP|.
415 void ec_precomp_select(const EC_GROUP *group, EC_PRECOMP *out, BN_ULONG mask,
416                        const EC_PRECOMP *a, const EC_PRECOMP *b);
417 
418 // ec_cmp_x_coordinate compares the x (affine) coordinate of |p|, mod the group
419 // order, with |r|. It returns one if the values match and zero if |p| is the
420 // point at infinity of the values do not match.
421 int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
422                         const EC_SCALAR *r);
423 
424 // ec_get_x_coordinate_as_scalar sets |*out| to |p|'s x-coordinate, modulo
425 // |group->order|. It returns one on success and zero if |p| is the point at
426 // infinity.
427 int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out,
428                                   const EC_RAW_POINT *p);
429 
430 // ec_get_x_coordinate_as_bytes writes |p|'s affine x-coordinate to |out|, which
431 // must have at must |max_out| bytes. It sets |*out_len| to the number of bytes
432 // written. The value is written big-endian and zero-padded to the size of the
433 // field. This function returns one on success and zero on failure.
434 int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out,
435                                  size_t *out_len, size_t max_out,
436                                  const EC_RAW_POINT *p);
437 
438 // ec_point_to_bytes behaves like |EC_POINT_point2oct| but takes an
439 // |EC_AFFINE|.
440 size_t ec_point_to_bytes(const EC_GROUP *group, const EC_AFFINE *point,
441                          point_conversion_form_t form, uint8_t *buf,
442                          size_t len);
443 
444 // ec_point_from_uncompressed parses |in| as a point in uncompressed form and
445 // sets the result to |out|. It returns one on success and zero if the input was
446 // invalid.
447 int ec_point_from_uncompressed(const EC_GROUP *group, EC_AFFINE *out,
448                                const uint8_t *in, size_t len);
449 
450 // ec_set_to_safe_point sets |out| to an arbitrary point on |group|, either the
451 // generator or the point at infinity. This is used to guard against callers of
452 // external APIs not checking the return value.
453 void ec_set_to_safe_point(const EC_GROUP *group, EC_RAW_POINT *out);
454 
455 // ec_affine_jacobian_equal returns one if |a| and |b| represent the same point
456 // and zero otherwise. It treats both inputs as secret.
457 int ec_affine_jacobian_equal(const EC_GROUP *group, const EC_AFFINE *a,
458                              const EC_RAW_POINT *b);
459 
460 
461 // Implementation details.
462 
463 struct ec_method_st {
464   int (*group_init)(EC_GROUP *);
465   void (*group_finish)(EC_GROUP *);
466   int (*group_set_curve)(EC_GROUP *, const BIGNUM *p, const BIGNUM *a,
467                          const BIGNUM *b, BN_CTX *);
468 
469   // point_get_affine_coordinates sets |*x| and |*y| to the affine coordinates
470   // of |p|. Either |x| or |y| may be NULL to omit it. It returns one on success
471   // and zero if |p| is the point at infinity.
472   int (*point_get_affine_coordinates)(const EC_GROUP *, const EC_RAW_POINT *p,
473                                       EC_FELEM *x, EC_FELEM *y);
474 
475   // jacobian_to_affine_batch implements |ec_jacobian_to_affine_batch|.
476   int (*jacobian_to_affine_batch)(const EC_GROUP *group, EC_AFFINE *out,
477                                   const EC_RAW_POINT *in, size_t num);
478 
479   // add sets |r| to |a| + |b|.
480   void (*add)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_RAW_POINT *a,
481               const EC_RAW_POINT *b);
482   // dbl sets |r| to |a| + |a|.
483   void (*dbl)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_RAW_POINT *a);
484 
485   // mul sets |r| to |scalar|*|p|.
486   void (*mul)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_RAW_POINT *p,
487               const EC_SCALAR *scalar);
488   // mul_base sets |r| to |scalar|*generator.
489   void (*mul_base)(const EC_GROUP *group, EC_RAW_POINT *r,
490                    const EC_SCALAR *scalar);
491   // mul_batch implements |ec_mul_scalar_batch|.
492   void (*mul_batch)(const EC_GROUP *group, EC_RAW_POINT *r,
493                     const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
494                     const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
495                     const EC_RAW_POINT *p2, const EC_SCALAR *scalar2);
496   // mul_public sets |r| to |g_scalar|*generator + |p_scalar|*|p|. It assumes
497   // that the inputs are public so there is no concern about leaking their
498   // values through timing.
499   //
500   // This function may be omitted if |mul_public_batch| is provided.
501   void (*mul_public)(const EC_GROUP *group, EC_RAW_POINT *r,
502                      const EC_SCALAR *g_scalar, const EC_RAW_POINT *p,
503                      const EC_SCALAR *p_scalar);
504   // mul_public_batch implements |ec_point_mul_scalar_public_batch|.
505   int (*mul_public_batch)(const EC_GROUP *group, EC_RAW_POINT *r,
506                           const EC_SCALAR *g_scalar, const EC_RAW_POINT *points,
507                           const EC_SCALAR *scalars, size_t num);
508 
509   // init_precomp implements |ec_init_precomp|.
510   int (*init_precomp)(const EC_GROUP *group, EC_PRECOMP *out,
511                       const EC_RAW_POINT *p);
512   // mul_precomp implements |ec_point_mul_scalar_precomp|.
513   void (*mul_precomp)(const EC_GROUP *group, EC_RAW_POINT *r,
514                       const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
515                       const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
516                       const EC_PRECOMP *p2, const EC_SCALAR *scalar2);
517 
518   // felem_mul and felem_sqr implement multiplication and squaring,
519   // respectively, so that the generic |EC_POINT_add| and |EC_POINT_dbl|
520   // implementations can work both with |EC_GFp_mont_method| and the tuned
521   // operations.
522   //
523   // TODO(davidben): This constrains |EC_FELEM|'s internal representation, adds
524   // many indirect calls in the middle of the generic code, and a bunch of
525   // conversions. If p224-64.c were easily convertable to Montgomery form, we
526   // could say |EC_FELEM| is always in Montgomery form. If we routed the rest of
527   // simple.c to |EC_METHOD|, we could give |EC_POINT| an |EC_METHOD|-specific
528   // representation and say |EC_FELEM| is purely a |EC_GFp_mont_method| type.
529   void (*felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
530                     const EC_FELEM *b);
531   void (*felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a);
532 
533   void (*felem_to_bytes)(const EC_GROUP *group, uint8_t *out, size_t *out_len,
534                          const EC_FELEM *in);
535   int (*felem_from_bytes)(const EC_GROUP *group, EC_FELEM *out,
536                           const uint8_t *in, size_t len);
537 
538   // felem_reduce sets |out| to |words|, reduced modulo the field size, p.
539   // |words| must be less than p^2. |num| must be at most twice the width of p.
540   // This function treats |words| as secret.
541   //
542   // This function is only used in hash-to-curve and may be omitted in curves
543   // that do not support it.
544   void (*felem_reduce)(const EC_GROUP *group, EC_FELEM *out,
545                        const BN_ULONG *words, size_t num);
546 
547   // felem_exp sets |out| to |a|^|exp|. It treats |a| is secret but |exp| as
548   // public.
549   //
550   // This function is used in hash-to-curve and may be NULL in curves not used
551   // with hash-to-curve.
552   void (*felem_exp)(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
553                     const BN_ULONG *exp, size_t num_exp);
554 
555   // scalar_inv0_montgomery implements |ec_scalar_inv0_montgomery|.
556   void (*scalar_inv0_montgomery)(const EC_GROUP *group, EC_SCALAR *out,
557                                  const EC_SCALAR *in);
558 
559   // scalar_to_montgomery_inv_vartime implements
560   // |ec_scalar_to_montgomery_inv_vartime|.
561   int (*scalar_to_montgomery_inv_vartime)(const EC_GROUP *group, EC_SCALAR *out,
562                                           const EC_SCALAR *in);
563 
564   // cmp_x_coordinate compares the x (affine) coordinate of |p|, mod the group
565   // order, with |r|. It returns one if the values match and zero if |p| is the
566   // point at infinity of the values do not match.
567   int (*cmp_x_coordinate)(const EC_GROUP *group, const EC_RAW_POINT *p,
568                           const EC_SCALAR *r);
569 } /* EC_METHOD */;
570 
571 const EC_METHOD *EC_GFp_mont_method(void);
572 
573 struct ec_group_st {
574   const EC_METHOD *meth;
575 
576   // Unlike all other |EC_POINT|s, |generator| does not own |generator->group|
577   // to avoid a reference cycle. Additionally, Z is guaranteed to be one, so X
578   // and Y are suitable for use as an |EC_AFFINE|.
579   EC_POINT *generator;
580   BIGNUM order;
581 
582   int curve_name;  // optional NID for named curve
583 
584   BN_MONT_CTX *order_mont;  // data for ECDSA inverse
585 
586   // The following members are handled by the method functions,
587   // even if they appear generic
588 
589   BIGNUM field;  // For curves over GF(p), this is the modulus.
590 
591   EC_FELEM a, b;  // Curve coefficients.
592 
593   // a_is_minus3 is one if |a| is -3 mod |field| and zero otherwise. Point
594   // arithmetic is optimized for -3.
595   int a_is_minus3;
596 
597   // field_greater_than_order is one if |field| is greate than |order| and zero
598   // otherwise.
599   int field_greater_than_order;
600 
601   // field_minus_order, if |field_greater_than_order| is true, is |field| minus
602   // |order| represented as an |EC_FELEM|. Otherwise, it is zero.
603   //
604   // Note: unlike |EC_FELEM|s used as intermediate values internal to the
605   // |EC_METHOD|, this value is not encoded in Montgomery form.
606   EC_FELEM field_minus_order;
607 
608   CRYPTO_refcount_t references;
609 
610   BN_MONT_CTX *mont;  // Montgomery structure.
611 
612   EC_FELEM one;  // The value one.
613 } /* EC_GROUP */;
614 
615 struct ec_point_st {
616   // group is an owning reference to |group|, unless this is
617   // |group->generator|.
618   EC_GROUP *group;
619   // raw is the group-specific point data. Functions that take |EC_POINT|
620   // typically check consistency with |EC_GROUP| while functions that take
621   // |EC_RAW_POINT| do not. Thus accesses to this field should be externally
622   // checked for consistency.
623   EC_RAW_POINT raw;
624 } /* EC_POINT */;
625 
626 EC_GROUP *ec_group_new(const EC_METHOD *meth);
627 
628 void ec_GFp_mont_mul(const EC_GROUP *group, EC_RAW_POINT *r,
629                      const EC_RAW_POINT *p, const EC_SCALAR *scalar);
630 void ec_GFp_mont_mul_base(const EC_GROUP *group, EC_RAW_POINT *r,
631                           const EC_SCALAR *scalar);
632 void ec_GFp_mont_mul_batch(const EC_GROUP *group, EC_RAW_POINT *r,
633                            const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
634                            const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
635                            const EC_RAW_POINT *p2, const EC_SCALAR *scalar2);
636 int ec_GFp_mont_init_precomp(const EC_GROUP *group, EC_PRECOMP *out,
637                              const EC_RAW_POINT *p);
638 void ec_GFp_mont_mul_precomp(const EC_GROUP *group, EC_RAW_POINT *r,
639                              const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
640                              const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
641                              const EC_PRECOMP *p2, const EC_SCALAR *scalar2);
642 
643 // ec_compute_wNAF writes the modified width-(w+1) Non-Adjacent Form (wNAF) of
644 // |scalar| to |out|. |out| must have room for |bits| + 1 elements, each of
645 // which will be either zero or odd with an absolute value less than  2^w
646 // satisfying
647 //     scalar = \sum_j out[j]*2^j
648 // where at most one of any  w+1  consecutive digits is non-zero
649 // with the exception that the most significant digit may be only
650 // w-1 zeros away from that next non-zero digit.
651 void ec_compute_wNAF(const EC_GROUP *group, int8_t *out,
652                      const EC_SCALAR *scalar, size_t bits, int w);
653 
654 int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_RAW_POINT *r,
655                                  const EC_SCALAR *g_scalar,
656                                  const EC_RAW_POINT *points,
657                                  const EC_SCALAR *scalars, size_t num);
658 
659 // method functions in simple.c
660 int ec_GFp_simple_group_init(EC_GROUP *);
661 void ec_GFp_simple_group_finish(EC_GROUP *);
662 int ec_GFp_simple_group_set_curve(EC_GROUP *, const BIGNUM *p, const BIGNUM *a,
663                                   const BIGNUM *b, BN_CTX *);
664 int ec_GFp_simple_group_get_curve(const EC_GROUP *, BIGNUM *p, BIGNUM *a,
665                                   BIGNUM *b);
666 void ec_GFp_simple_point_init(EC_RAW_POINT *);
667 void ec_GFp_simple_point_copy(EC_RAW_POINT *, const EC_RAW_POINT *);
668 void ec_GFp_simple_point_set_to_infinity(const EC_GROUP *, EC_RAW_POINT *);
669 void ec_GFp_mont_add(const EC_GROUP *, EC_RAW_POINT *r, const EC_RAW_POINT *a,
670                      const EC_RAW_POINT *b);
671 void ec_GFp_mont_dbl(const EC_GROUP *, EC_RAW_POINT *r, const EC_RAW_POINT *a);
672 void ec_GFp_simple_invert(const EC_GROUP *, EC_RAW_POINT *);
673 int ec_GFp_simple_is_at_infinity(const EC_GROUP *, const EC_RAW_POINT *);
674 int ec_GFp_simple_is_on_curve(const EC_GROUP *, const EC_RAW_POINT *);
675 int ec_GFp_simple_points_equal(const EC_GROUP *, const EC_RAW_POINT *a,
676                                const EC_RAW_POINT *b);
677 void ec_simple_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r,
678                                       const EC_SCALAR *a);
679 
680 int ec_simple_scalar_to_montgomery_inv_vartime(const EC_GROUP *group,
681                                                EC_SCALAR *r,
682                                                const EC_SCALAR *a);
683 
684 int ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
685                                    const EC_SCALAR *r);
686 
687 void ec_GFp_simple_felem_to_bytes(const EC_GROUP *group, uint8_t *out,
688                                   size_t *out_len, const EC_FELEM *in);
689 int ec_GFp_simple_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out,
690                                    const uint8_t *in, size_t len);
691 
692 // method functions in montgomery.c
693 int ec_GFp_mont_group_init(EC_GROUP *);
694 int ec_GFp_mont_group_set_curve(EC_GROUP *, const BIGNUM *p, const BIGNUM *a,
695                                 const BIGNUM *b, BN_CTX *);
696 void ec_GFp_mont_group_finish(EC_GROUP *);
697 void ec_GFp_mont_felem_mul(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
698                            const EC_FELEM *b);
699 void ec_GFp_mont_felem_sqr(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a);
700 
701 void ec_GFp_mont_felem_to_bytes(const EC_GROUP *group, uint8_t *out,
702                                 size_t *out_len, const EC_FELEM *in);
703 int ec_GFp_mont_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out,
704                                  const uint8_t *in, size_t len);
705 
706 void ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, crypto_word_t *digit,
707                                      crypto_word_t in);
708 
709 const EC_METHOD *EC_GFp_nistp224_method(void);
710 const EC_METHOD *EC_GFp_nistp256_method(void);
711 
712 // EC_GFp_nistz256_method is a GFp method using montgomery multiplication, with
713 // x86-64 optimized P256. See http://eprint.iacr.org/2013/816.
714 const EC_METHOD *EC_GFp_nistz256_method(void);
715 
716 // An EC_WRAPPED_SCALAR is an |EC_SCALAR| with a parallel |BIGNUM|
717 // representation. It exists to support the |EC_KEY_get0_private_key| API.
718 typedef struct {
719   BIGNUM bignum;
720   EC_SCALAR scalar;
721 } EC_WRAPPED_SCALAR;
722 
723 struct ec_key_st {
724   EC_GROUP *group;
725 
726   // Ideally |pub_key| would be an |EC_AFFINE| so serializing it does not pay an
727   // inversion each time, but the |EC_KEY_get0_public_key| API implies public
728   // keys are stored in an |EC_POINT|-compatible form.
729   EC_POINT *pub_key;
730   EC_WRAPPED_SCALAR *priv_key;
731 
732   // fixed_k may contain a specific value of 'k', to be used in ECDSA signing.
733   // This is only for the FIPS power-on tests.
734   BIGNUM *fixed_k;
735 
736   unsigned int enc_flag;
737   point_conversion_form_t conv_form;
738 
739   CRYPTO_refcount_t references;
740 
741   ECDSA_METHOD *ecdsa_meth;
742 
743   CRYPTO_EX_DATA ex_data;
744 } /* EC_KEY */;
745 
746 struct built_in_curve {
747   int nid;
748   const uint8_t *oid;
749   uint8_t oid_len;
750   // comment is a human-readable string describing the curve.
751   const char *comment;
752   // param_len is the number of bytes needed to store a field element.
753   uint8_t param_len;
754   // params points to an array of 6*|param_len| bytes which hold the field
755   // elements of the following (in big-endian order): prime, a, b, generator x,
756   // generator y, order.
757   const uint8_t *params;
758   const EC_METHOD *method;
759 };
760 
761 #define OPENSSL_NUM_BUILT_IN_CURVES 4
762 
763 struct built_in_curves {
764   struct built_in_curve curves[OPENSSL_NUM_BUILT_IN_CURVES];
765 };
766 
767 // OPENSSL_built_in_curves returns a pointer to static information about
768 // standard curves. The array is terminated with an entry where |nid| is
769 // |NID_undef|.
770 const struct built_in_curves *OPENSSL_built_in_curves(void);
771 
772 #if defined(__cplusplus)
773 }  // extern C
774 #endif
775 
776 #endif  // OPENSSL_HEADER_EC_INTERNAL_H
777