text
[RRG-proxmark3.git] / common / mbedtls / ecp.c
blob5754cfe28d2b6209904d3fb27725f1403a651afc
1 /*
2 * Elliptic curves over GF(p): generic functions
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 * References:
23 * SEC1 http://www.secg.org/index.php?action=secg,docs_secg
24 * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone
25 * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
26 * RFC 4492 for the related TLS structures and constants
27 * RFC 7748 for the Curve448 and Curve25519 curve definitions
29 * [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf
31 * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
32 * for elliptic curve cryptosystems. In : Cryptographic Hardware and
33 * Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
34 * <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
36 * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
37 * render ECC resistant against Side Channel Attacks. IACR Cryptology
38 * ePrint Archive, 2004, vol. 2004, p. 342.
39 * <http://eprint.iacr.org/2004/342.pdf>
42 #include "common.h"
44 /**
45 * \brief Function level alternative implementation.
47 * The MBEDTLS_ECP_INTERNAL_ALT macro enables alternative implementations to
48 * replace certain functions in this module. The alternative implementations are
49 * typically hardware accelerators and need to activate the hardware before the
50 * computation starts and deactivate it after it finishes. The
51 * mbedtls_internal_ecp_init() and mbedtls_internal_ecp_free() functions serve
52 * this purpose.
54 * To preserve the correct functionality the following conditions must hold:
56 * - The alternative implementation must be activated by
57 * mbedtls_internal_ecp_init() before any of the replaceable functions is
58 * called.
59 * - mbedtls_internal_ecp_free() must \b only be called when the alternative
60 * implementation is activated.
61 * - mbedtls_internal_ecp_init() must \b not be called when the alternative
62 * implementation is activated.
63 * - Public functions must not return while the alternative implementation is
64 * activated.
65 * - Replaceable functions are guarded by \c MBEDTLS_ECP_XXX_ALT macros and
66 * before calling them an \code if( mbedtls_internal_ecp_grp_capable( grp ) )
67 * \endcode ensures that the alternative implementation supports the current
68 * group.
70 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
71 #endif
73 #if defined(MBEDTLS_ECP_C)
75 #include "mbedtls/ecp.h"
76 #include "mbedtls/threading.h"
77 #include "mbedtls/platform_util.h"
78 #include "mbedtls/error.h"
80 #include <string.h>
82 #if !defined(MBEDTLS_ECP_ALT)
84 /* Parameter validation macros based on platform_util.h */
85 #define ECP_VALIDATE_RET( cond ) \
86 MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA )
87 #define ECP_VALIDATE( cond ) \
88 MBEDTLS_INTERNAL_VALIDATE( cond )
90 #if defined(MBEDTLS_PLATFORM_C)
91 #include "mbedtls/platform.h"
92 #else
93 #include <stdlib.h>
94 #include <stdio.h>
95 #define mbedtls_printf printf
96 #define mbedtls_calloc calloc
97 #define mbedtls_free free
98 #endif
100 #include "mbedtls/ecp_internal.h"
102 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
103 #if defined(MBEDTLS_HMAC_DRBG_C)
104 #include "mbedtls/hmac_drbg.h"
105 #elif defined(MBEDTLS_CTR_DRBG_C)
106 #include "mbedtls/ctr_drbg.h"
107 #else
108 #error "Invalid configuration detected. Include check_config.h to ensure that the configuration is valid."
109 #endif
110 #endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */
112 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
113 !defined(inline) && !defined(__cplusplus)
114 #define inline __inline
115 #endif
117 #if defined(MBEDTLS_SELF_TEST)
119 * Counts of point addition and doubling, and field multiplications.
120 * Used to test resistance of point multiplication to simple timing attacks.
122 static unsigned long add_count, dbl_count, mul_count;
123 #endif
125 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
127 * Currently ecp_mul() takes a RNG function as an argument, used for
128 * side-channel protection, but it can be NULL. The initial reasoning was
129 * that people will pass non-NULL RNG when they care about side-channels, but
130 * unfortunately we have some APIs that call ecp_mul() with a NULL RNG, with
131 * no opportunity for the user to do anything about it.
133 * The obvious strategies for addressing that include:
134 * - change those APIs so that they take RNG arguments;
135 * - require a global RNG to be available to all crypto modules.
137 * Unfortunately those would break compatibility. So what we do instead is
138 * have our own internal DRBG instance, seeded from the secret scalar.
140 * The following is a light-weight abstraction layer for doing that with
141 * HMAC_DRBG (first choice) or CTR_DRBG.
144 #if defined(MBEDTLS_HMAC_DRBG_C)
146 /* DRBG context type */
147 typedef mbedtls_hmac_drbg_context ecp_drbg_context;
149 /* DRBG context init */
150 static inline void ecp_drbg_init(ecp_drbg_context *ctx) {
151 mbedtls_hmac_drbg_init(ctx);
154 /* DRBG context free */
155 static inline void ecp_drbg_free(ecp_drbg_context *ctx) {
156 mbedtls_hmac_drbg_free(ctx);
159 /* DRBG function */
160 static inline int ecp_drbg_random(void *p_rng,
161 unsigned char *output, size_t output_len) {
162 return (mbedtls_hmac_drbg_random(p_rng, output, output_len));
165 /* DRBG context seeding */
166 static int ecp_drbg_seed(ecp_drbg_context *ctx,
167 const mbedtls_mpi *secret, size_t secret_len) {
168 int ret;
169 unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES];
170 /* The list starts with strong hashes */
171 const mbedtls_md_type_t md_type = mbedtls_md_list()[0];
172 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type);
174 if (secret_len > MBEDTLS_ECP_MAX_BYTES) {
175 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
176 goto cleanup;
179 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(secret,
180 secret_bytes, secret_len));
182 ret = mbedtls_hmac_drbg_seed_buf(ctx, md_info, secret_bytes, secret_len);
184 cleanup:
185 mbedtls_platform_zeroize(secret_bytes, secret_len);
187 return (ret);
190 #elif defined(MBEDTLS_CTR_DRBG_C)
192 /* DRBG context type */
193 typedef mbedtls_ctr_drbg_context ecp_drbg_context;
195 /* DRBG context init */
196 static inline void ecp_drbg_init(ecp_drbg_context *ctx) {
197 mbedtls_ctr_drbg_init(ctx);
200 /* DRBG context free */
201 static inline void ecp_drbg_free(ecp_drbg_context *ctx) {
202 mbedtls_ctr_drbg_free(ctx);
205 /* DRBG function */
206 static inline int ecp_drbg_random(void *p_rng,
207 unsigned char *output, size_t output_len) {
208 return (mbedtls_ctr_drbg_random(p_rng, output, output_len));
212 * Since CTR_DRBG doesn't have a seed_buf() function the way HMAC_DRBG does,
213 * we need to pass an entropy function when seeding. So we use a dummy
214 * function for that, and pass the actual entropy as customisation string.
215 * (During seeding of CTR_DRBG the entropy input and customisation string are
216 * concatenated before being used to update the secret state.)
218 static int ecp_ctr_drbg_null_entropy(void *ctx, unsigned char *out, size_t len) {
219 (void) ctx;
220 memset(out, 0, len);
221 return (0);
224 /* DRBG context seeding */
225 static int ecp_drbg_seed(ecp_drbg_context *ctx,
226 const mbedtls_mpi *secret, size_t secret_len) {
227 int ret;
228 unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES];
230 if (secret_len > MBEDTLS_ECP_MAX_BYTES) {
231 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
232 goto cleanup;
235 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(secret,
236 secret_bytes, secret_len));
238 ret = mbedtls_ctr_drbg_seed(ctx, ecp_ctr_drbg_null_entropy, NULL,
239 secret_bytes, secret_len);
241 cleanup:
242 mbedtls_platform_zeroize(secret_bytes, secret_len);
244 return (ret);
247 #else
248 #error "Invalid configuration detected. Include check_config.h to ensure that the configuration is valid."
249 #endif /* DRBG modules */
250 #endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */
252 #if defined(MBEDTLS_ECP_RESTARTABLE)
254 * Maximum number of "basic operations" to be done in a row.
256 * Default value 0 means that ECC operations will not yield.
257 * Note that regardless of the value of ecp_max_ops, always at
258 * least one step is performed before yielding.
260 * Setting ecp_max_ops=1 can be suitable for testing purposes
261 * as it will interrupt computation at all possible points.
263 static unsigned ecp_max_ops = 0;
266 * Set ecp_max_ops
268 void mbedtls_ecp_set_max_ops(unsigned max_ops) {
269 ecp_max_ops = max_ops;
273 * Check if restart is enabled
275 int mbedtls_ecp_restart_is_enabled(void) {
276 return (ecp_max_ops != 0);
280 * Restart sub-context for ecp_mul_comb()
282 struct mbedtls_ecp_restart_mul {
283 mbedtls_ecp_point R; /* current intermediate result */
284 size_t i; /* current index in various loops, 0 outside */
285 mbedtls_ecp_point *T; /* table for precomputed points */
286 unsigned char T_size; /* number of points in table T */
287 enum { /* what were we doing last time we returned? */
288 ecp_rsm_init = 0, /* nothing so far, dummy initial state */
289 ecp_rsm_pre_dbl, /* precompute 2^n multiples */
290 ecp_rsm_pre_norm_dbl, /* normalize precomputed 2^n multiples */
291 ecp_rsm_pre_add, /* precompute remaining points by adding */
292 ecp_rsm_pre_norm_add, /* normalize all precomputed points */
293 ecp_rsm_comb_core, /* ecp_mul_comb_core() */
294 ecp_rsm_final_norm, /* do the final normalization */
295 } state;
296 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
297 ecp_drbg_context drbg_ctx;
298 unsigned char drbg_seeded;
299 #endif
303 * Init restart_mul sub-context
305 static void ecp_restart_rsm_init(mbedtls_ecp_restart_mul_ctx *ctx) {
306 mbedtls_ecp_point_init(&ctx->R);
307 ctx->i = 0;
308 ctx->T = NULL;
309 ctx->T_size = 0;
310 ctx->state = ecp_rsm_init;
311 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
312 ecp_drbg_init(&ctx->drbg_ctx);
313 ctx->drbg_seeded = 0;
314 #endif
318 * Free the components of a restart_mul sub-context
320 static void ecp_restart_rsm_free(mbedtls_ecp_restart_mul_ctx *ctx) {
321 unsigned char i;
323 if (ctx == NULL)
324 return;
326 mbedtls_ecp_point_free(&ctx->R);
328 if (ctx->T != NULL) {
329 for (i = 0; i < ctx->T_size; i++)
330 mbedtls_ecp_point_free(ctx->T + i);
331 mbedtls_free(ctx->T);
334 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
335 ecp_drbg_free(&ctx->drbg_ctx);
336 #endif
338 ecp_restart_rsm_init(ctx);
342 * Restart context for ecp_muladd()
344 struct mbedtls_ecp_restart_muladd {
345 mbedtls_ecp_point mP; /* mP value */
346 mbedtls_ecp_point R; /* R intermediate result */
347 enum { /* what should we do next? */
348 ecp_rsma_mul1 = 0, /* first multiplication */
349 ecp_rsma_mul2, /* second multiplication */
350 ecp_rsma_add, /* addition */
351 ecp_rsma_norm, /* normalization */
352 } state;
356 * Init restart_muladd sub-context
358 static void ecp_restart_ma_init(mbedtls_ecp_restart_muladd_ctx *ctx) {
359 mbedtls_ecp_point_init(&ctx->mP);
360 mbedtls_ecp_point_init(&ctx->R);
361 ctx->state = ecp_rsma_mul1;
365 * Free the components of a restart_muladd sub-context
367 static void ecp_restart_ma_free(mbedtls_ecp_restart_muladd_ctx *ctx) {
368 if (ctx == NULL)
369 return;
371 mbedtls_ecp_point_free(&ctx->mP);
372 mbedtls_ecp_point_free(&ctx->R);
374 ecp_restart_ma_init(ctx);
378 * Initialize a restart context
380 void mbedtls_ecp_restart_init(mbedtls_ecp_restart_ctx *ctx) {
381 ECP_VALIDATE(ctx != NULL);
382 ctx->ops_done = 0;
383 ctx->depth = 0;
384 ctx->rsm = NULL;
385 ctx->ma = NULL;
389 * Free the components of a restart context
391 void mbedtls_ecp_restart_free(mbedtls_ecp_restart_ctx *ctx) {
392 if (ctx == NULL)
393 return;
395 ecp_restart_rsm_free(ctx->rsm);
396 mbedtls_free(ctx->rsm);
398 ecp_restart_ma_free(ctx->ma);
399 mbedtls_free(ctx->ma);
401 mbedtls_ecp_restart_init(ctx);
405 * Check if we can do the next step
407 int mbedtls_ecp_check_budget(const mbedtls_ecp_group *grp,
408 mbedtls_ecp_restart_ctx *rs_ctx,
409 unsigned ops) {
410 ECP_VALIDATE_RET(grp != NULL);
412 if (rs_ctx != NULL && ecp_max_ops != 0) {
413 /* scale depending on curve size: the chosen reference is 256-bit,
414 * and multiplication is quadratic. Round to the closest integer. */
415 if (grp->pbits >= 512)
416 ops *= 4;
417 else if (grp->pbits >= 384)
418 ops *= 2;
420 /* Avoid infinite loops: always allow first step.
421 * Because of that, however, it's not generally true
422 * that ops_done <= ecp_max_ops, so the check
423 * ops_done > ecp_max_ops below is mandatory. */
424 if ((rs_ctx->ops_done != 0) &&
425 (rs_ctx->ops_done > ecp_max_ops ||
426 ops > ecp_max_ops - rs_ctx->ops_done)) {
427 return (MBEDTLS_ERR_ECP_IN_PROGRESS);
430 /* update running count */
431 rs_ctx->ops_done += ops;
434 return (0);
437 /* Call this when entering a function that needs its own sub-context */
438 #define ECP_RS_ENTER( SUB ) do { \
439 /* reset ops count for this call if top-level */ \
440 if( rs_ctx != NULL && rs_ctx->depth++ == 0 ) \
441 rs_ctx->ops_done = 0; \
443 /* set up our own sub-context if needed */ \
444 if( mbedtls_ecp_restart_is_enabled() && \
445 rs_ctx != NULL && rs_ctx->SUB == NULL ) \
447 rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \
448 if( rs_ctx->SUB == NULL ) \
449 return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \
451 ecp_restart_## SUB ##_init( rs_ctx->SUB ); \
453 } while( 0 )
455 /* Call this when leaving a function that needs its own sub-context */
456 #define ECP_RS_LEAVE( SUB ) do { \
457 /* clear our sub-context when not in progress (done or error) */ \
458 if( rs_ctx != NULL && rs_ctx->SUB != NULL && \
459 ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \
461 ecp_restart_## SUB ##_free( rs_ctx->SUB ); \
462 mbedtls_free( rs_ctx->SUB ); \
463 rs_ctx->SUB = NULL; \
466 if( rs_ctx != NULL ) \
467 rs_ctx->depth--; \
468 } while( 0 )
470 #else /* MBEDTLS_ECP_RESTARTABLE */
472 #define ECP_RS_ENTER( sub ) (void) rs_ctx;
473 #define ECP_RS_LEAVE( sub ) (void) rs_ctx;
475 #endif /* MBEDTLS_ECP_RESTARTABLE */
478 * List of supported curves:
479 * - internal ID
480 * - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2, RFC 8446 sec. 4.2.7)
481 * - size in bits
482 * - readable name
484 * Curves are listed in order: largest curves first, and for a given size,
485 * fastest curves first. This provides the default order for the SSL module.
487 * Reminder: update profiles in x509_crt.c when adding a new curves!
489 static const mbedtls_ecp_curve_info ecp_supported_curves[] = {
490 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
491 { MBEDTLS_ECP_DP_SECP521R1, 25, 521, "secp521r1" },
492 #endif
493 #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
494 { MBEDTLS_ECP_DP_BP512R1, 28, 512, "brainpoolP512r1" },
495 #endif
496 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
497 { MBEDTLS_ECP_DP_SECP384R1, 24, 384, "secp384r1" },
498 #endif
499 #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
500 { MBEDTLS_ECP_DP_BP384R1, 27, 384, "brainpoolP384r1" },
501 #endif
502 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
503 { MBEDTLS_ECP_DP_SECP256R1, 23, 256, "secp256r1" },
504 #endif
505 #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
506 { MBEDTLS_ECP_DP_SECP256K1, 22, 256, "secp256k1" },
507 #endif
508 #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
509 { MBEDTLS_ECP_DP_BP256R1, 26, 256, "brainpoolP256r1" },
510 #endif
511 #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
512 { MBEDTLS_ECP_DP_SECP224R1, 21, 224, "secp224r1" },
513 #endif
514 #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
515 { MBEDTLS_ECP_DP_SECP224K1, 20, 224, "secp224k1" },
516 #endif
517 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
518 { MBEDTLS_ECP_DP_SECP192R1, 19, 192, "secp192r1" },
519 #endif
520 #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
521 { MBEDTLS_ECP_DP_SECP192K1, 18, 192, "secp192k1" },
522 #endif
523 #if defined(MBEDTLS_ECP_DP_SECP128R1_ENABLED)
524 { MBEDTLS_ECP_DP_SECP128R1, 0xFE00, 128, "secp128r1" },
525 #endif
526 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
527 { MBEDTLS_ECP_DP_CURVE25519, 29, 256, "x25519" },
528 #endif
529 #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
530 { MBEDTLS_ECP_DP_CURVE448, 30, 448, "x448" },
531 #endif
532 { MBEDTLS_ECP_DP_NONE, 0, 0, NULL },
535 #define ECP_NB_CURVES sizeof( ecp_supported_curves ) / \
536 sizeof( ecp_supported_curves[0] )
538 static mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES];
541 * List of supported curves and associated info
543 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list(void) {
544 return (ecp_supported_curves);
548 * List of supported curves, group ID only
550 const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list(void) {
551 static int init_done = 0;
553 if (! init_done) {
554 size_t i = 0;
555 const mbedtls_ecp_curve_info *curve_info;
557 for (curve_info = mbedtls_ecp_curve_list();
558 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
559 curve_info++) {
560 ecp_supported_grp_id[i++] = curve_info->grp_id;
562 ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE;
564 init_done = 1;
567 return (ecp_supported_grp_id);
571 * Get the curve info for the internal identifier
573 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id(mbedtls_ecp_group_id grp_id) {
574 const mbedtls_ecp_curve_info *curve_info;
576 for (curve_info = mbedtls_ecp_curve_list();
577 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
578 curve_info++) {
579 if (curve_info->grp_id == grp_id)
580 return (curve_info);
583 return (NULL);
587 * Get the curve info from the TLS identifier
589 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id(uint16_t tls_id) {
590 const mbedtls_ecp_curve_info *curve_info;
592 for (curve_info = mbedtls_ecp_curve_list();
593 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
594 curve_info++) {
595 if (curve_info->tls_id == tls_id)
596 return (curve_info);
599 return (NULL);
603 * Get the curve info from the name
605 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name(const char *name) {
606 const mbedtls_ecp_curve_info *curve_info;
608 if (name == NULL)
609 return (NULL);
611 for (curve_info = mbedtls_ecp_curve_list();
612 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
613 curve_info++) {
614 if (strcmp(curve_info->name, name) == 0)
615 return (curve_info);
618 return (NULL);
622 * Get the type of a curve
624 mbedtls_ecp_curve_type mbedtls_ecp_get_type(const mbedtls_ecp_group *grp) {
625 if (grp->G.X.p == NULL)
626 return (MBEDTLS_ECP_TYPE_NONE);
628 if (grp->G.Y.p == NULL)
629 return (MBEDTLS_ECP_TYPE_MONTGOMERY);
630 else
631 return (MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS);
635 * Initialize (the components of) a point
637 void mbedtls_ecp_point_init(mbedtls_ecp_point *pt) {
638 ECP_VALIDATE(pt != NULL);
640 mbedtls_mpi_init(&pt->X);
641 mbedtls_mpi_init(&pt->Y);
642 mbedtls_mpi_init(&pt->Z);
646 * Initialize (the components of) a group
648 void mbedtls_ecp_group_init(mbedtls_ecp_group *grp) {
649 ECP_VALIDATE(grp != NULL);
651 grp->id = MBEDTLS_ECP_DP_NONE;
652 mbedtls_mpi_init(&grp->P);
653 mbedtls_mpi_init(&grp->A);
654 mbedtls_mpi_init(&grp->B);
655 mbedtls_ecp_point_init(&grp->G);
656 mbedtls_mpi_init(&grp->N);
657 grp->pbits = 0;
658 grp->nbits = 0;
659 grp->h = 0;
660 grp->modp = NULL;
661 grp->t_pre = NULL;
662 grp->t_post = NULL;
663 grp->t_data = NULL;
664 grp->T = NULL;
665 grp->T_size = 0;
669 * Initialize (the components of) a key pair
671 void mbedtls_ecp_keypair_init(mbedtls_ecp_keypair *key) {
672 ECP_VALIDATE(key != NULL);
674 mbedtls_ecp_group_init(&key->grp);
675 mbedtls_mpi_init(&key->d);
676 mbedtls_ecp_point_init(&key->Q);
680 * Unallocate (the components of) a point
682 void mbedtls_ecp_point_free(mbedtls_ecp_point *pt) {
683 if (pt == NULL)
684 return;
686 mbedtls_mpi_free(&(pt->X));
687 mbedtls_mpi_free(&(pt->Y));
688 mbedtls_mpi_free(&(pt->Z));
692 * Unallocate (the components of) a group
694 void mbedtls_ecp_group_free(mbedtls_ecp_group *grp) {
695 size_t i;
697 if (grp == NULL)
698 return;
700 if (grp->h != 1) {
701 mbedtls_mpi_free(&grp->P);
702 mbedtls_mpi_free(&grp->A);
703 mbedtls_mpi_free(&grp->B);
704 mbedtls_ecp_point_free(&grp->G);
705 mbedtls_mpi_free(&grp->N);
708 if (grp->T != NULL) {
709 for (i = 0; i < grp->T_size; i++)
710 mbedtls_ecp_point_free(&grp->T[i]);
711 mbedtls_free(grp->T);
714 mbedtls_platform_zeroize(grp, sizeof(mbedtls_ecp_group));
718 * Unallocate (the components of) a key pair
720 void mbedtls_ecp_keypair_free(mbedtls_ecp_keypair *key) {
721 if (key == NULL)
722 return;
724 mbedtls_ecp_group_free(&key->grp);
725 mbedtls_mpi_free(&key->d);
726 mbedtls_ecp_point_free(&key->Q);
730 * Copy the contents of a point
732 int mbedtls_ecp_copy(mbedtls_ecp_point *P, const mbedtls_ecp_point *Q) {
733 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
734 ECP_VALIDATE_RET(P != NULL);
735 ECP_VALIDATE_RET(Q != NULL);
737 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->X, &Q->X));
738 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->Y, &Q->Y));
739 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->Z, &Q->Z));
741 cleanup:
742 return (ret);
746 * Copy the contents of a group object
748 int mbedtls_ecp_group_copy(mbedtls_ecp_group *dst, const mbedtls_ecp_group *src) {
749 ECP_VALIDATE_RET(dst != NULL);
750 ECP_VALIDATE_RET(src != NULL);
752 return (mbedtls_ecp_group_load(dst, src->id));
756 * Set point to zero
758 int mbedtls_ecp_set_zero(mbedtls_ecp_point *pt) {
759 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
760 ECP_VALIDATE_RET(pt != NULL);
762 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->X, 1));
763 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Y, 1));
764 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 0));
766 cleanup:
767 return (ret);
771 * Tell if a point is zero
773 int mbedtls_ecp_is_zero(mbedtls_ecp_point *pt) {
774 ECP_VALIDATE_RET(pt != NULL);
776 return (mbedtls_mpi_cmp_int(&pt->Z, 0) == 0);
780 * Compare two points lazily
782 int mbedtls_ecp_point_cmp(const mbedtls_ecp_point *P,
783 const mbedtls_ecp_point *Q) {
784 ECP_VALIDATE_RET(P != NULL);
785 ECP_VALIDATE_RET(Q != NULL);
787 if (mbedtls_mpi_cmp_mpi(&P->X, &Q->X) == 0 &&
788 mbedtls_mpi_cmp_mpi(&P->Y, &Q->Y) == 0 &&
789 mbedtls_mpi_cmp_mpi(&P->Z, &Q->Z) == 0) {
790 return (0);
793 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
797 * Import a non-zero point from ASCII strings
799 int mbedtls_ecp_point_read_string(mbedtls_ecp_point *P, int radix,
800 const char *x, const char *y) {
801 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
802 ECP_VALIDATE_RET(P != NULL);
803 ECP_VALIDATE_RET(x != NULL);
804 ECP_VALIDATE_RET(y != NULL);
806 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&P->X, radix, x));
807 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&P->Y, radix, y));
808 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&P->Z, 1));
810 cleanup:
811 return (ret);
815 * Export a point into unsigned binary data (SEC1 2.3.3 and RFC7748)
817 int mbedtls_ecp_point_write_binary(const mbedtls_ecp_group *grp,
818 const mbedtls_ecp_point *P,
819 int format, size_t *olen,
820 unsigned char *buf, size_t buflen) {
821 int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
822 size_t plen;
823 ECP_VALIDATE_RET(grp != NULL);
824 ECP_VALIDATE_RET(P != NULL);
825 ECP_VALIDATE_RET(olen != NULL);
826 ECP_VALIDATE_RET(buf != NULL);
827 ECP_VALIDATE_RET(format == MBEDTLS_ECP_PF_UNCOMPRESSED ||
828 format == MBEDTLS_ECP_PF_COMPRESSED);
830 plen = mbedtls_mpi_size(&grp->P);
832 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
833 (void) format; /* Montgomery curves always use the same point format */
834 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
835 *olen = plen;
836 if (buflen < *olen)
837 return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
839 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary_le(&P->X, buf, plen));
841 #endif
842 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
843 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
845 * Common case: P == 0
847 if (mbedtls_mpi_cmp_int(&P->Z, 0) == 0) {
848 if (buflen < 1)
849 return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
851 buf[0] = 0x00;
852 *olen = 1;
854 return (0);
857 if (format == MBEDTLS_ECP_PF_UNCOMPRESSED) {
858 *olen = 2 * plen + 1;
860 if (buflen < *olen)
861 return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
863 buf[0] = 0x04;
864 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->X, buf + 1, plen));
865 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->Y, buf + 1 + plen, plen));
866 } else if (format == MBEDTLS_ECP_PF_COMPRESSED) {
867 *olen = plen + 1;
869 if (buflen < *olen)
870 return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
872 buf[0] = 0x02 + mbedtls_mpi_get_bit(&P->Y, 0);
873 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->X, buf + 1, plen));
876 #endif
878 cleanup:
879 return (ret);
883 * Import a point from unsigned binary data (SEC1 2.3.4 and RFC7748)
885 int mbedtls_ecp_point_read_binary(const mbedtls_ecp_group *grp,
886 mbedtls_ecp_point *pt,
887 const unsigned char *buf, size_t ilen) {
888 int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
889 size_t plen;
890 ECP_VALIDATE_RET(grp != NULL);
891 ECP_VALIDATE_RET(pt != NULL);
892 ECP_VALIDATE_RET(buf != NULL);
894 if (ilen < 1)
895 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
897 plen = mbedtls_mpi_size(&grp->P);
899 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
900 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
901 if (plen != ilen)
902 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
904 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&pt->X, buf, plen));
905 mbedtls_mpi_free(&pt->Y);
907 if (grp->id == MBEDTLS_ECP_DP_CURVE25519)
908 /* Set most significant bit to 0 as prescribed in RFC7748 §5 */
909 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&pt->X, plen * 8 - 1, 0));
911 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 1));
913 #endif
914 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
915 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
916 if (buf[0] == 0x00) {
917 if (ilen == 1)
918 return (mbedtls_ecp_set_zero(pt));
919 else
920 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
923 if (buf[0] != 0x04)
924 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
926 if (ilen != 2 * plen + 1)
927 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
929 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&pt->X, buf + 1, plen));
930 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&pt->Y,
931 buf + 1 + plen, plen));
932 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 1));
934 #endif
936 cleanup:
937 return (ret);
941 * Import a point from a TLS ECPoint record (RFC 4492)
942 * struct {
943 * opaque point <1..2^8-1>;
944 * } ECPoint;
946 int mbedtls_ecp_tls_read_point(const mbedtls_ecp_group *grp,
947 mbedtls_ecp_point *pt,
948 const unsigned char **buf, size_t buf_len) {
949 unsigned char data_len;
950 const unsigned char *buf_start;
951 ECP_VALIDATE_RET(grp != NULL);
952 ECP_VALIDATE_RET(pt != NULL);
953 ECP_VALIDATE_RET(buf != NULL);
954 ECP_VALIDATE_RET(*buf != NULL);
957 * We must have at least two bytes (1 for length, at least one for data)
959 if (buf_len < 2)
960 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
962 data_len = *(*buf)++;
963 if (data_len < 1 || data_len > buf_len - 1)
964 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
967 * Save buffer start for read_binary and update buf
969 buf_start = *buf;
970 *buf += data_len;
972 return (mbedtls_ecp_point_read_binary(grp, pt, buf_start, data_len));
976 * Export a point as a TLS ECPoint record (RFC 4492)
977 * struct {
978 * opaque point <1..2^8-1>;
979 * } ECPoint;
981 int mbedtls_ecp_tls_write_point(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,
982 int format, size_t *olen,
983 unsigned char *buf, size_t blen) {
984 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
985 ECP_VALIDATE_RET(grp != NULL);
986 ECP_VALIDATE_RET(pt != NULL);
987 ECP_VALIDATE_RET(olen != NULL);
988 ECP_VALIDATE_RET(buf != NULL);
989 ECP_VALIDATE_RET(format == MBEDTLS_ECP_PF_UNCOMPRESSED ||
990 format == MBEDTLS_ECP_PF_COMPRESSED);
993 * buffer length must be at least one, for our length byte
995 if (blen < 1)
996 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
998 if ((ret = mbedtls_ecp_point_write_binary(grp, pt, format,
999 olen, buf + 1, blen - 1)) != 0)
1000 return (ret);
1003 * write length to the first byte and update total length
1005 buf[0] = (unsigned char) * olen;
1006 ++*olen;
1008 return (0);
1012 * Set a group from an ECParameters record (RFC 4492)
1014 int mbedtls_ecp_tls_read_group(mbedtls_ecp_group *grp,
1015 const unsigned char **buf, size_t len) {
1016 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1017 mbedtls_ecp_group_id grp_id;
1018 ECP_VALIDATE_RET(grp != NULL);
1019 ECP_VALIDATE_RET(buf != NULL);
1020 ECP_VALIDATE_RET(*buf != NULL);
1022 if ((ret = mbedtls_ecp_tls_read_group_id(&grp_id, buf, len)) != 0)
1023 return (ret);
1025 return (mbedtls_ecp_group_load(grp, grp_id));
1029 * Read a group id from an ECParameters record (RFC 4492) and convert it to
1030 * mbedtls_ecp_group_id.
1032 int mbedtls_ecp_tls_read_group_id(mbedtls_ecp_group_id *grp,
1033 const unsigned char **buf, size_t len) {
1034 uint16_t tls_id;
1035 const mbedtls_ecp_curve_info *curve_info;
1036 ECP_VALIDATE_RET(grp != NULL);
1037 ECP_VALIDATE_RET(buf != NULL);
1038 ECP_VALIDATE_RET(*buf != NULL);
1041 * We expect at least three bytes (see below)
1043 if (len < 3)
1044 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
1047 * First byte is curve_type; only named_curve is handled
1049 if (*(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE)
1050 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
1053 * Next two bytes are the namedcurve value
1055 tls_id = *(*buf)++;
1056 tls_id <<= 8;
1057 tls_id |= *(*buf)++;
1059 if ((curve_info = mbedtls_ecp_curve_info_from_tls_id(tls_id)) == NULL)
1060 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
1062 *grp = curve_info->grp_id;
1064 return (0);
1068 * Write the ECParameters record corresponding to a group (RFC 4492)
1070 int mbedtls_ecp_tls_write_group(const mbedtls_ecp_group *grp, size_t *olen,
1071 unsigned char *buf, size_t blen) {
1072 const mbedtls_ecp_curve_info *curve_info;
1073 ECP_VALIDATE_RET(grp != NULL);
1074 ECP_VALIDATE_RET(buf != NULL);
1075 ECP_VALIDATE_RET(olen != NULL);
1077 if ((curve_info = mbedtls_ecp_curve_info_from_grp_id(grp->id)) == NULL)
1078 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
1081 * We are going to write 3 bytes (see below)
1083 *olen = 3;
1084 if (blen < *olen)
1085 return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
1088 * First byte is curve_type, always named_curve
1090 *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
1093 * Next two bytes are the namedcurve value
1095 buf[0] = curve_info->tls_id >> 8;
1096 buf[1] = curve_info->tls_id & 0xFF;
1098 return (0);
1102 * Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi.
1103 * See the documentation of struct mbedtls_ecp_group.
1105 * This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf.
1107 static int ecp_modp(mbedtls_mpi *N, const mbedtls_ecp_group *grp) {
1108 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1110 if (grp->modp == NULL)
1111 return (mbedtls_mpi_mod_mpi(N, N, &grp->P));
1113 /* N->s < 0 is a much faster test, which fails only if N is 0 */
1114 if ((N->s < 0 && mbedtls_mpi_cmp_int(N, 0) != 0) ||
1115 mbedtls_mpi_bitlen(N) > 2 * grp->pbits) {
1116 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
1119 MBEDTLS_MPI_CHK(grp->modp(N));
1121 /* N->s < 0 is a much faster test, which fails only if N is 0 */
1122 while (N->s < 0 && mbedtls_mpi_cmp_int(N, 0) != 0)
1123 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(N, N, &grp->P));
1125 while (mbedtls_mpi_cmp_mpi(N, &grp->P) >= 0)
1126 /* we known P, N and the result are positive */
1127 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(N, N, &grp->P));
1129 cleanup:
1130 return (ret);
1134 * Fast mod-p functions expect their argument to be in the 0..p^2 range.
1136 * In order to guarantee that, we need to ensure that operands of
1137 * mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will
1138 * bring the result back to this range.
1140 * The following macros are shortcuts for doing that.
1144 * Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi
1146 #if defined(MBEDTLS_SELF_TEST)
1147 #define INC_MUL_COUNT mul_count++;
1148 #else
1149 #define INC_MUL_COUNT
1150 #endif
1152 #define MOD_MUL( N ) \
1153 do \
1155 MBEDTLS_MPI_CHK( ecp_modp( &(N), grp ) ); \
1156 INC_MUL_COUNT \
1157 } while( 0 )
1159 static int mbedtls_mpi_mul_mod(const mbedtls_ecp_group *grp,
1160 mbedtls_mpi *X,
1161 const mbedtls_mpi *A,
1162 const mbedtls_mpi *B) {
1163 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1164 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(X, A, B));
1165 MOD_MUL(*X);
1166 cleanup:
1167 return (ret);
1171 * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi
1172 * N->s < 0 is a very fast test, which fails only if N is 0
1174 #define MOD_SUB( N ) \
1175 while( (N).s < 0 && mbedtls_mpi_cmp_int( &(N), 0 ) != 0 ) \
1176 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &(N), &(N), &grp->P ) )
1178 #if ( defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) && \
1179 !( defined(MBEDTLS_ECP_NO_FALLBACK) && \
1180 defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && \
1181 defined(MBEDTLS_ECP_ADD_MIXED_ALT) ) ) || \
1182 ( defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) && \
1183 !( defined(MBEDTLS_ECP_NO_FALLBACK) && \
1184 defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) ) )
1185 static int mbedtls_mpi_sub_mod(const mbedtls_ecp_group *grp,
1186 mbedtls_mpi *X,
1187 const mbedtls_mpi *A,
1188 const mbedtls_mpi *B) {
1189 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1190 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(X, A, B));
1191 MOD_SUB(*X);
1192 cleanup:
1193 return (ret);
1195 #endif /* All functions referencing mbedtls_mpi_sub_mod() are alt-implemented without fallback */
1198 * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int.
1199 * We known P, N and the result are positive, so sub_abs is correct, and
1200 * a bit faster.
1202 #define MOD_ADD( N ) \
1203 while( mbedtls_mpi_cmp_mpi( &(N), &grp->P ) >= 0 ) \
1204 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &(N), &(N), &grp->P ) )
1206 static int mbedtls_mpi_add_mod(const mbedtls_ecp_group *grp,
1207 mbedtls_mpi *X,
1208 const mbedtls_mpi *A,
1209 const mbedtls_mpi *B) {
1210 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1211 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(X, A, B));
1212 MOD_ADD(*X);
1213 cleanup:
1214 return (ret);
1217 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) && \
1218 !( defined(MBEDTLS_ECP_NO_FALLBACK) && \
1219 defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && \
1220 defined(MBEDTLS_ECP_ADD_MIXED_ALT) )
1221 static int mbedtls_mpi_shift_l_mod(const mbedtls_ecp_group *grp,
1222 mbedtls_mpi *X,
1223 size_t count) {
1224 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1225 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(X, count));
1226 MOD_ADD(*X);
1227 cleanup:
1228 return (ret);
1230 #endif /* All functions referencing mbedtls_mpi_shift_l_mod() are alt-implemented without fallback */
1232 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
1234 * For curves in short Weierstrass form, we do all the internal operations in
1235 * Jacobian coordinates.
1237 * For multiplication, we'll use a comb method with coutermeasueres against
1238 * SPA, hence timing attacks.
1242 * Normalize jacobian coordinates so that Z == 0 || Z == 1 (GECC 3.2.1)
1243 * Cost: 1N := 1I + 3M + 1S
1245 static int ecp_normalize_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt) {
1246 if (mbedtls_mpi_cmp_int(&pt->Z, 0) == 0)
1247 return (0);
1249 #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
1250 if (mbedtls_internal_ecp_grp_capable(grp))
1251 return (mbedtls_internal_ecp_normalize_jac(grp, pt));
1252 #endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */
1254 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
1255 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
1256 #else
1257 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1258 mbedtls_mpi Zi, ZZi;
1259 mbedtls_mpi_init(&Zi);
1260 mbedtls_mpi_init(&ZZi);
1263 * X = X / Z^2 mod p
1265 MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&Zi, &pt->Z, &grp->P));
1266 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &ZZi, &Zi, &Zi));
1267 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &pt->X, &pt->X, &ZZi));
1270 * Y = Y / Z^3 mod p
1272 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &pt->Y, &pt->Y, &ZZi));
1273 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &pt->Y, &pt->Y, &Zi));
1276 * Z = 1
1278 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 1));
1280 cleanup:
1282 mbedtls_mpi_free(&Zi);
1283 mbedtls_mpi_free(&ZZi);
1285 return (ret);
1286 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) */
1290 * Normalize jacobian coordinates of an array of (pointers to) points,
1291 * using Montgomery's trick to perform only one inversion mod P.
1292 * (See for example Cohen's "A Course in Computational Algebraic Number
1293 * Theory", Algorithm 10.3.4.)
1295 * Warning: fails (returning an error) if one of the points is zero!
1296 * This should never happen, see choice of w in ecp_mul_comb().
1298 * Cost: 1N(t) := 1I + (6t - 3)M + 1S
1300 static int ecp_normalize_jac_many(const mbedtls_ecp_group *grp,
1301 mbedtls_ecp_point *T[], size_t T_size) {
1302 if (T_size < 2)
1303 return (ecp_normalize_jac(grp, *T));
1305 #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
1306 if (mbedtls_internal_ecp_grp_capable(grp))
1307 return (mbedtls_internal_ecp_normalize_jac_many(grp, T, T_size));
1308 #endif
1310 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
1311 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
1312 #else
1313 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1314 size_t i;
1315 mbedtls_mpi *c, u, Zi, ZZi;
1317 if ((c = mbedtls_calloc(T_size, sizeof(mbedtls_mpi))) == NULL)
1318 return (MBEDTLS_ERR_ECP_ALLOC_FAILED);
1320 for (i = 0; i < T_size; i++)
1321 mbedtls_mpi_init(&c[i]);
1323 mbedtls_mpi_init(&u);
1324 mbedtls_mpi_init(&Zi);
1325 mbedtls_mpi_init(&ZZi);
1328 * c[i] = Z_0 * ... * Z_i
1330 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&c[0], &T[0]->Z));
1331 for (i = 1; i < T_size; i++) {
1332 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &c[i], &c[i - 1], &T[i]->Z));
1336 * u = 1 / (Z_0 * ... * Z_n) mod P
1338 MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&u, &c[T_size - 1], &grp->P));
1340 for (i = T_size - 1; ; i--) {
1342 * Zi = 1 / Z_i mod p
1343 * u = 1 / (Z_0 * ... * Z_i) mod P
1345 if (i == 0) {
1346 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&Zi, &u));
1347 } else {
1348 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &Zi, &u, &c[i - 1]));
1349 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &u, &u, &T[i]->Z));
1353 * proceed as in normalize()
1355 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &ZZi, &Zi, &Zi));
1356 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T[i]->X, &T[i]->X, &ZZi));
1357 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T[i]->Y, &T[i]->Y, &ZZi));
1358 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T[i]->Y, &T[i]->Y, &Zi));
1361 * Post-precessing: reclaim some memory by shrinking coordinates
1362 * - not storing Z (always 1)
1363 * - shrinking other coordinates, but still keeping the same number of
1364 * limbs as P, as otherwise it will too likely be regrown too fast.
1366 MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(&T[i]->X, grp->P.n));
1367 MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(&T[i]->Y, grp->P.n));
1368 mbedtls_mpi_free(&T[i]->Z);
1370 if (i == 0)
1371 break;
1374 cleanup:
1376 mbedtls_mpi_free(&u);
1377 mbedtls_mpi_free(&Zi);
1378 mbedtls_mpi_free(&ZZi);
1379 for (i = 0; i < T_size; i++)
1380 mbedtls_mpi_free(&c[i]);
1381 mbedtls_free(c);
1383 return (ret);
1384 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) */
1388 * Conditional point inversion: Q -> -Q = (Q.X, -Q.Y, Q.Z) without leak.
1389 * "inv" must be 0 (don't invert) or 1 (invert) or the result will be invalid
1391 static int ecp_safe_invert_jac(const mbedtls_ecp_group *grp,
1392 mbedtls_ecp_point *Q,
1393 unsigned char inv) {
1394 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1395 unsigned char nonzero;
1396 mbedtls_mpi mQY;
1398 mbedtls_mpi_init(&mQY);
1400 /* Use the fact that -Q.Y mod P = P - Q.Y unless Q.Y == 0 */
1401 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&mQY, &grp->P, &Q->Y));
1402 nonzero = mbedtls_mpi_cmp_int(&Q->Y, 0) != 0;
1403 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(&Q->Y, &mQY, inv & nonzero));
1405 cleanup:
1406 mbedtls_mpi_free(&mQY);
1408 return (ret);
1412 * Point doubling R = 2 P, Jacobian coordinates
1414 * Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 .
1416 * We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR
1417 * (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring.
1419 * Standard optimizations are applied when curve parameter A is one of { 0, -3 }.
1421 * Cost: 1D := 3M + 4S (A == 0)
1422 * 4M + 4S (A == -3)
1423 * 3M + 6S + 1a otherwise
1425 static int ecp_double_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1426 const mbedtls_ecp_point *P) {
1427 #if defined(MBEDTLS_SELF_TEST)
1428 dbl_count++;
1429 #endif
1431 #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
1432 if (mbedtls_internal_ecp_grp_capable(grp))
1433 return (mbedtls_internal_ecp_double_jac(grp, R, P));
1434 #endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */
1436 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
1437 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
1438 #else
1439 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1440 mbedtls_mpi M, S, T, U;
1442 mbedtls_mpi_init(&M);
1443 mbedtls_mpi_init(&S);
1444 mbedtls_mpi_init(&T);
1445 mbedtls_mpi_init(&U);
1447 /* Special case for A = -3 */
1448 if (grp->A.p == NULL) {
1449 /* M = 3(X + Z^2)(X - Z^2) */
1450 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S, &P->Z, &P->Z));
1451 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &T, &P->X, &S));
1452 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &U, &P->X, &S));
1453 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S, &T, &U));
1454 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&M, &S, 3));
1455 MOD_ADD(M);
1456 } else {
1457 /* M = 3.X^2 */
1458 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S, &P->X, &P->X));
1459 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&M, &S, 3));
1460 MOD_ADD(M);
1462 /* Optimize away for "koblitz" curves with A = 0 */
1463 if (mbedtls_mpi_cmp_int(&grp->A, 0) != 0) {
1464 /* M += A.Z^4 */
1465 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S, &P->Z, &P->Z));
1466 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T, &S, &S));
1467 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S, &T, &grp->A));
1468 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &M, &M, &S));
1472 /* S = 4.X.Y^2 */
1473 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T, &P->Y, &P->Y));
1474 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l_mod(grp, &T, 1));
1475 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S, &P->X, &T));
1476 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l_mod(grp, &S, 1));
1478 /* U = 8.Y^4 */
1479 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &U, &T, &T));
1480 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l_mod(grp, &U, 1));
1482 /* T = M^2 - 2.S */
1483 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T, &M, &M));
1484 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &T, &T, &S));
1485 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &T, &T, &S));
1487 /* S = M(S - T) - U */
1488 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &S, &S, &T));
1489 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S, &S, &M));
1490 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &S, &S, &U));
1492 /* U = 2.Y.Z */
1493 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &U, &P->Y, &P->Z));
1494 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l_mod(grp, &U, 1));
1496 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R->X, &T));
1497 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R->Y, &S));
1498 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R->Z, &U));
1500 cleanup:
1501 mbedtls_mpi_free(&M);
1502 mbedtls_mpi_free(&S);
1503 mbedtls_mpi_free(&T);
1504 mbedtls_mpi_free(&U);
1506 return (ret);
1507 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) */
1511 * Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22)
1513 * The coordinates of Q must be normalized (= affine),
1514 * but those of P don't need to. R is not normalized.
1516 * Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q.
1517 * None of these cases can happen as intermediate step in ecp_mul_comb():
1518 * - at each step, P, Q and R are multiples of the base point, the factor
1519 * being less than its order, so none of them is zero;
1520 * - Q is an odd multiple of the base point, P an even multiple,
1521 * due to the choice of precomputed points in the modified comb method.
1522 * So branches for these cases do not leak secret information.
1524 * We accept Q->Z being unset (saving memory in tables) as meaning 1.
1526 * Cost: 1A := 8M + 3S
1528 static int ecp_add_mixed(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1529 const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q) {
1530 #if defined(MBEDTLS_SELF_TEST)
1531 add_count++;
1532 #endif
1534 #if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
1535 if (mbedtls_internal_ecp_grp_capable(grp))
1536 return (mbedtls_internal_ecp_add_mixed(grp, R, P, Q));
1537 #endif /* MBEDTLS_ECP_ADD_MIXED_ALT */
1539 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_ADD_MIXED_ALT)
1540 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
1541 #else
1542 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1543 mbedtls_mpi T1, T2, T3, T4, X, Y, Z;
1546 * Trivial cases: P == 0 or Q == 0 (case 1)
1548 if (mbedtls_mpi_cmp_int(&P->Z, 0) == 0)
1549 return (mbedtls_ecp_copy(R, Q));
1551 if (Q->Z.p != NULL && mbedtls_mpi_cmp_int(&Q->Z, 0) == 0)
1552 return (mbedtls_ecp_copy(R, P));
1555 * Make sure Q coordinates are normalized
1557 if (Q->Z.p != NULL && mbedtls_mpi_cmp_int(&Q->Z, 1) != 0)
1558 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
1560 mbedtls_mpi_init(&T1);
1561 mbedtls_mpi_init(&T2);
1562 mbedtls_mpi_init(&T3);
1563 mbedtls_mpi_init(&T4);
1564 mbedtls_mpi_init(&X);
1565 mbedtls_mpi_init(&Y);
1566 mbedtls_mpi_init(&Z);
1568 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T1, &P->Z, &P->Z));
1569 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T2, &T1, &P->Z));
1570 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T1, &T1, &Q->X));
1571 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T2, &T2, &Q->Y));
1572 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &T1, &T1, &P->X));
1573 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &T2, &T2, &P->Y));
1575 /* Special cases (2) and (3) */
1576 if (mbedtls_mpi_cmp_int(&T1, 0) == 0) {
1577 if (mbedtls_mpi_cmp_int(&T2, 0) == 0) {
1578 ret = ecp_double_jac(grp, R, P);
1579 goto cleanup;
1580 } else {
1581 ret = mbedtls_ecp_set_zero(R);
1582 goto cleanup;
1586 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &Z, &P->Z, &T1));
1587 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T3, &T1, &T1));
1588 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T4, &T3, &T1));
1589 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T3, &T3, &P->X));
1590 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&T1, &T3));
1591 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l_mod(grp, &T1, 1));
1592 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &X, &T2, &T2));
1593 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &X, &X, &T1));
1594 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &X, &X, &T4));
1595 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &T3, &T3, &X));
1596 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T3, &T3, &T2));
1597 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &T4, &T4, &P->Y));
1598 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &Y, &T3, &T4));
1600 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R->X, &X));
1601 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R->Y, &Y));
1602 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R->Z, &Z));
1604 cleanup:
1606 mbedtls_mpi_free(&T1);
1607 mbedtls_mpi_free(&T2);
1608 mbedtls_mpi_free(&T3);
1609 mbedtls_mpi_free(&T4);
1610 mbedtls_mpi_free(&X);
1611 mbedtls_mpi_free(&Y);
1612 mbedtls_mpi_free(&Z);
1614 return (ret);
1615 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_ADD_MIXED_ALT) */
1619 * Randomize jacobian coordinates:
1620 * (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l
1621 * This is sort of the reverse operation of ecp_normalize_jac().
1623 * This countermeasure was first suggested in [2].
1625 static int ecp_randomize_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,
1626 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) {
1627 #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
1628 if (mbedtls_internal_ecp_grp_capable(grp))
1629 return (mbedtls_internal_ecp_randomize_jac(grp, pt, f_rng, p_rng));
1630 #endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */
1632 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
1633 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
1634 #else
1635 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1636 mbedtls_mpi l, ll;
1637 int count = 0;
1638 size_t p_size = (grp->pbits + 7) / 8;
1640 mbedtls_mpi_init(&l);
1641 mbedtls_mpi_init(&ll);
1643 /* Generate l such that 1 < l < p */
1644 do {
1645 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&l, p_size, f_rng, p_rng));
1647 while (mbedtls_mpi_cmp_mpi(&l, &grp->P) >= 0)
1648 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&l, 1));
1650 if (count++ > 10) {
1651 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
1652 goto cleanup;
1654 } while (mbedtls_mpi_cmp_int(&l, 1) <= 0);
1656 /* Z = l * Z */
1657 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &pt->Z, &pt->Z, &l));
1659 /* X = l^2 * X */
1660 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &ll, &l, &l));
1661 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &pt->X, &pt->X, &ll));
1663 /* Y = l^3 * Y */
1664 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &ll, &ll, &l));
1665 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &pt->Y, &pt->Y, &ll));
1667 cleanup:
1668 mbedtls_mpi_free(&l);
1669 mbedtls_mpi_free(&ll);
1671 return (ret);
1672 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) */
1676 * Check and define parameters used by the comb method (see below for details)
1678 #if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7
1679 #error "MBEDTLS_ECP_WINDOW_SIZE out of bounds"
1680 #endif
1682 /* d = ceil( n / w ) */
1683 #define COMB_MAX_D ( MBEDTLS_ECP_MAX_BITS + 1 ) / 2
1685 /* number of precomputed points */
1686 #define COMB_MAX_PRE ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) )
1689 * Compute the representation of m that will be used with our comb method.
1691 * The basic comb method is described in GECC 3.44 for example. We use a
1692 * modified version that provides resistance to SPA by avoiding zero
1693 * digits in the representation as in [3]. We modify the method further by
1694 * requiring that all K_i be odd, which has the small cost that our
1695 * representation uses one more K_i, due to carries, but saves on the size of
1696 * the precomputed table.
1698 * Summary of the comb method and its modifications:
1700 * - The goal is to compute m*P for some w*d-bit integer m.
1702 * - The basic comb method splits m into the w-bit integers
1703 * x[0] .. x[d-1] where x[i] consists of the bits in m whose
1704 * index has residue i modulo d, and computes m * P as
1705 * S[x[0]] + 2 * S[x[1]] + .. + 2^(d-1) S[x[d-1]], where
1706 * S[i_{w-1} .. i_0] := i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + i_0 P.
1708 * - If it happens that, say, x[i+1]=0 (=> S[x[i+1]]=0), one can replace the sum by
1709 * .. + 2^{i-1} S[x[i-1]] - 2^i S[x[i]] + 2^{i+1} S[x[i]] + 2^{i+2} S[x[i+2]] ..,
1710 * thereby successively converting it into a form where all summands
1711 * are nonzero, at the cost of negative summands. This is the basic idea of [3].
1713 * - More generally, even if x[i+1] != 0, we can first transform the sum as
1714 * .. - 2^i S[x[i]] + 2^{i+1} ( S[x[i]] + S[x[i+1]] ) + 2^{i+2} S[x[i+2]] ..,
1715 * and then replace S[x[i]] + S[x[i+1]] = S[x[i] ^ x[i+1]] + 2 S[x[i] & x[i+1]].
1716 * Performing and iterating this procedure for those x[i] that are even
1717 * (keeping track of carry), we can transform the original sum into one of the form
1718 * S[x'[0]] +- 2 S[x'[1]] +- .. +- 2^{d-1} S[x'[d-1]] + 2^d S[x'[d]]
1719 * with all x'[i] odd. It is therefore only necessary to know S at odd indices,
1720 * which is why we are only computing half of it in the first place in
1721 * ecp_precompute_comb and accessing it with index abs(i) / 2 in ecp_select_comb.
1723 * - For the sake of compactness, only the seven low-order bits of x[i]
1724 * are used to represent its absolute value (K_i in the paper), and the msb
1725 * of x[i] encodes the sign (s_i in the paper): it is set if and only if
1726 * if s_i == -1;
1728 * Calling conventions:
1729 * - x is an array of size d + 1
1730 * - w is the size, ie number of teeth, of the comb, and must be between
1731 * 2 and 7 (in practice, between 2 and MBEDTLS_ECP_WINDOW_SIZE)
1732 * - m is the MPI, expected to be odd and such that bitlength(m) <= w * d
1733 * (the result will be incorrect if these assumptions are not satisfied)
1735 static void ecp_comb_recode_core(unsigned char x[], size_t d,
1736 unsigned char w, const mbedtls_mpi *m) {
1737 size_t i, j;
1738 unsigned char c, cc, adjust;
1740 memset(x, 0, d + 1);
1742 /* First get the classical comb values (except for x_d = 0) */
1743 for (i = 0; i < d; i++)
1744 for (j = 0; j < w; j++)
1745 x[i] |= mbedtls_mpi_get_bit(m, i + d * j) << j;
1747 /* Now make sure x_1 .. x_d are odd */
1748 c = 0;
1749 for (i = 1; i <= d; i++) {
1750 /* Add carry and update it */
1751 cc = x[i] & c;
1752 x[i] = x[i] ^ c;
1753 c = cc;
1755 /* Adjust if needed, avoiding branches */
1756 adjust = 1 - (x[i] & 0x01);
1757 c |= x[i] & (x[i - 1] * adjust);
1758 x[i] = x[i] ^ (x[i - 1] * adjust);
1759 x[i - 1] |= adjust << 7;
1764 * Precompute points for the adapted comb method
1766 * Assumption: T must be able to hold 2^{w - 1} elements.
1768 * Operation: If i = i_{w-1} ... i_1 is the binary representation of i,
1769 * sets T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P.
1771 * Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1)
1773 * Note: Even comb values (those where P would be omitted from the
1774 * sum defining T[i] above) are not needed in our adaption
1775 * the comb method. See ecp_comb_recode_core().
1777 * This function currently works in four steps:
1778 * (1) [dbl] Computation of intermediate T[i] for 2-power values of i
1779 * (2) [norm_dbl] Normalization of coordinates of these T[i]
1780 * (3) [add] Computation of all T[i]
1781 * (4) [norm_add] Normalization of all T[i]
1783 * Step 1 can be interrupted but not the others; together with the final
1784 * coordinate normalization they are the largest steps done at once, depending
1785 * on the window size. Here are operation counts for P-256:
1787 * step (2) (3) (4)
1788 * w = 5 142 165 208
1789 * w = 4 136 77 160
1790 * w = 3 130 33 136
1791 * w = 2 124 11 124
1793 * So if ECC operations are blocking for too long even with a low max_ops
1794 * value, it's useful to set MBEDTLS_ECP_WINDOW_SIZE to a lower value in order
1795 * to minimize maximum blocking time.
1797 static int ecp_precompute_comb(const mbedtls_ecp_group *grp,
1798 mbedtls_ecp_point T[], const mbedtls_ecp_point *P,
1799 unsigned char w, size_t d,
1800 mbedtls_ecp_restart_ctx *rs_ctx) {
1801 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1802 unsigned char i;
1803 size_t j = 0;
1804 const unsigned char T_size = 1U << (w - 1);
1805 mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1];
1807 #if defined(MBEDTLS_ECP_RESTARTABLE)
1808 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
1809 if (rs_ctx->rsm->state == ecp_rsm_pre_dbl)
1810 goto dbl;
1811 if (rs_ctx->rsm->state == ecp_rsm_pre_norm_dbl)
1812 goto norm_dbl;
1813 if (rs_ctx->rsm->state == ecp_rsm_pre_add)
1814 goto add;
1815 if (rs_ctx->rsm->state == ecp_rsm_pre_norm_add)
1816 goto norm_add;
1818 #else
1819 (void) rs_ctx;
1820 #endif
1822 #if defined(MBEDTLS_ECP_RESTARTABLE)
1823 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
1824 rs_ctx->rsm->state = ecp_rsm_pre_dbl;
1826 /* initial state for the loop */
1827 rs_ctx->rsm->i = 0;
1830 dbl:
1831 #endif
1833 * Set T[0] = P and
1834 * T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value)
1836 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(&T[0], P));
1838 #if defined(MBEDTLS_ECP_RESTARTABLE)
1839 if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0)
1840 j = rs_ctx->rsm->i;
1841 else
1842 #endif
1843 j = 0;
1845 for (; j < d * (w - 1); j++) {
1846 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_DBL);
1848 i = 1U << (j / d);
1849 cur = T + i;
1851 if (j % d == 0)
1852 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(cur, T + (i >> 1)));
1854 MBEDTLS_MPI_CHK(ecp_double_jac(grp, cur, cur));
1857 #if defined(MBEDTLS_ECP_RESTARTABLE)
1858 if (rs_ctx != NULL && rs_ctx->rsm != NULL)
1859 rs_ctx->rsm->state = ecp_rsm_pre_norm_dbl;
1861 norm_dbl:
1862 #endif
1864 * Normalize current elements in T. As T has holes,
1865 * use an auxiliary array of pointers to elements in T.
1867 j = 0;
1868 for (i = 1; i < T_size; i <<= 1)
1869 TT[j++] = T + i;
1871 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV + 6 * j - 2);
1873 MBEDTLS_MPI_CHK(ecp_normalize_jac_many(grp, TT, j));
1875 #if defined(MBEDTLS_ECP_RESTARTABLE)
1876 if (rs_ctx != NULL && rs_ctx->rsm != NULL)
1877 rs_ctx->rsm->state = ecp_rsm_pre_add;
1879 add:
1880 #endif
1882 * Compute the remaining ones using the minimal number of additions
1883 * Be careful to update T[2^l] only after using it!
1885 MBEDTLS_ECP_BUDGET((T_size - 1) * MBEDTLS_ECP_OPS_ADD);
1887 for (i = 1; i < T_size; i <<= 1) {
1888 j = i;
1889 while (j--)
1890 MBEDTLS_MPI_CHK(ecp_add_mixed(grp, &T[i + j], &T[j], &T[i]));
1893 #if defined(MBEDTLS_ECP_RESTARTABLE)
1894 if (rs_ctx != NULL && rs_ctx->rsm != NULL)
1895 rs_ctx->rsm->state = ecp_rsm_pre_norm_add;
1897 norm_add:
1898 #endif
1900 * Normalize final elements in T. Even though there are no holes now, we
1901 * still need the auxiliary array for homogeneity with the previous
1902 * call. Also, skip T[0] which is already normalised, being a copy of P.
1904 for (j = 0; j + 1 < T_size; j++)
1905 TT[j] = T + j + 1;
1907 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV + 6 * j - 2);
1909 MBEDTLS_MPI_CHK(ecp_normalize_jac_many(grp, TT, j));
1911 cleanup:
1912 #if defined(MBEDTLS_ECP_RESTARTABLE)
1913 if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
1914 ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
1915 if (rs_ctx->rsm->state == ecp_rsm_pre_dbl)
1916 rs_ctx->rsm->i = j;
1918 #endif
1920 return (ret);
1924 * Select precomputed point: R = sign(i) * T[ abs(i) / 2 ]
1926 * See ecp_comb_recode_core() for background
1928 static int ecp_select_comb(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1929 const mbedtls_ecp_point T[], unsigned char T_size,
1930 unsigned char i) {
1931 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1932 unsigned char ii, j;
1934 /* Ignore the "sign" bit and scale down */
1935 ii = (i & 0x7Fu) >> 1;
1937 /* Read the whole table to thwart cache-based timing attacks */
1938 for (j = 0; j < T_size; j++) {
1939 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(&R->X, &T[j].X, j == ii));
1940 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(&R->Y, &T[j].Y, j == ii));
1943 /* Safely invert result if i is "negative" */
1944 MBEDTLS_MPI_CHK(ecp_safe_invert_jac(grp, R, i >> 7));
1946 cleanup:
1947 return (ret);
1951 * Core multiplication algorithm for the (modified) comb method.
1952 * This part is actually common with the basic comb method (GECC 3.44)
1954 * Cost: d A + d D + 1 R
1956 static int ecp_mul_comb_core(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1957 const mbedtls_ecp_point T[], unsigned char T_size,
1958 const unsigned char x[], size_t d,
1959 int (*f_rng)(void *, unsigned char *, size_t),
1960 void *p_rng,
1961 mbedtls_ecp_restart_ctx *rs_ctx) {
1962 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1963 mbedtls_ecp_point Txi;
1964 size_t i;
1966 mbedtls_ecp_point_init(&Txi);
1968 #if !defined(MBEDTLS_ECP_RESTARTABLE)
1969 (void) rs_ctx;
1970 #endif
1972 #if defined(MBEDTLS_ECP_RESTARTABLE)
1973 if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
1974 rs_ctx->rsm->state != ecp_rsm_comb_core) {
1975 rs_ctx->rsm->i = 0;
1976 rs_ctx->rsm->state = ecp_rsm_comb_core;
1979 /* new 'if' instead of nested for the sake of the 'else' branch */
1980 if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0) {
1981 /* restore current index (R already pointing to rs_ctx->rsm->R) */
1982 i = rs_ctx->rsm->i;
1983 } else
1984 #endif
1986 /* Start with a non-zero point and randomize its coordinates */
1987 i = d;
1988 MBEDTLS_MPI_CHK(ecp_select_comb(grp, R, T, T_size, x[i]));
1989 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1));
1990 #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
1991 if (f_rng != 0)
1992 #endif
1993 MBEDTLS_MPI_CHK(ecp_randomize_jac(grp, R, f_rng, p_rng));
1996 while (i != 0) {
1997 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_DBL + MBEDTLS_ECP_OPS_ADD);
1998 --i;
2000 MBEDTLS_MPI_CHK(ecp_double_jac(grp, R, R));
2001 MBEDTLS_MPI_CHK(ecp_select_comb(grp, &Txi, T, T_size, x[i]));
2002 MBEDTLS_MPI_CHK(ecp_add_mixed(grp, R, R, &Txi));
2005 cleanup:
2007 mbedtls_ecp_point_free(&Txi);
2009 #if defined(MBEDTLS_ECP_RESTARTABLE)
2010 if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
2011 ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2012 rs_ctx->rsm->i = i;
2013 /* no need to save R, already pointing to rs_ctx->rsm->R */
2015 #endif
2017 return (ret);
2021 * Recode the scalar to get constant-time comb multiplication
2023 * As the actual scalar recoding needs an odd scalar as a starting point,
2024 * this wrapper ensures that by replacing m by N - m if necessary, and
2025 * informs the caller that the result of multiplication will be negated.
2027 * This works because we only support large prime order for Short Weierstrass
2028 * curves, so N is always odd hence either m or N - m is.
2030 * See ecp_comb_recode_core() for background.
2032 static int ecp_comb_recode_scalar(const mbedtls_ecp_group *grp,
2033 const mbedtls_mpi *m,
2034 unsigned char k[COMB_MAX_D + 1],
2035 size_t d,
2036 unsigned char w,
2037 unsigned char *parity_trick) {
2038 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2039 mbedtls_mpi M, mm;
2041 mbedtls_mpi_init(&M);
2042 mbedtls_mpi_init(&mm);
2044 /* N is always odd (see above), just make extra sure */
2045 if (mbedtls_mpi_get_bit(&grp->N, 0) != 1)
2046 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
2048 /* do we need the parity trick? */
2049 *parity_trick = (mbedtls_mpi_get_bit(m, 0) == 0);
2051 /* execute parity fix in constant time */
2052 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&M, m));
2053 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&mm, &grp->N, m));
2054 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(&M, &mm, *parity_trick));
2056 /* actual scalar recoding */
2057 ecp_comb_recode_core(k, d, w, &M);
2059 cleanup:
2060 mbedtls_mpi_free(&mm);
2061 mbedtls_mpi_free(&M);
2063 return (ret);
2067 * Perform comb multiplication (for short Weierstrass curves)
2068 * once the auxiliary table has been pre-computed.
2070 * Scalar recoding may use a parity trick that makes us compute -m * P,
2071 * if that is the case we'll need to recover m * P at the end.
2073 static int ecp_mul_comb_after_precomp(const mbedtls_ecp_group *grp,
2074 mbedtls_ecp_point *R,
2075 const mbedtls_mpi *m,
2076 const mbedtls_ecp_point *T,
2077 unsigned char T_size,
2078 unsigned char w,
2079 size_t d,
2080 int (*f_rng)(void *, unsigned char *, size_t),
2081 void *p_rng,
2082 mbedtls_ecp_restart_ctx *rs_ctx) {
2083 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2084 unsigned char parity_trick;
2085 unsigned char k[COMB_MAX_D + 1];
2086 mbedtls_ecp_point *RR = R;
2088 #if defined(MBEDTLS_ECP_RESTARTABLE)
2089 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
2090 RR = &rs_ctx->rsm->R;
2092 if (rs_ctx->rsm->state == ecp_rsm_final_norm)
2093 goto final_norm;
2095 #endif
2097 MBEDTLS_MPI_CHK(ecp_comb_recode_scalar(grp, m, k, d, w,
2098 &parity_trick));
2099 MBEDTLS_MPI_CHK(ecp_mul_comb_core(grp, RR, T, T_size, k, d,
2100 f_rng, p_rng, rs_ctx));
2101 MBEDTLS_MPI_CHK(ecp_safe_invert_jac(grp, RR, parity_trick));
2103 #if defined(MBEDTLS_ECP_RESTARTABLE)
2104 if (rs_ctx != NULL && rs_ctx->rsm != NULL)
2105 rs_ctx->rsm->state = ecp_rsm_final_norm;
2107 final_norm:
2108 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV);
2109 #endif
2111 * Knowledge of the jacobian coordinates may leak the last few bits of the
2112 * scalar [1], and since our MPI implementation isn't constant-flow,
2113 * inversion (used for coordinate normalization) may leak the full value
2114 * of its input via side-channels [2].
2116 * [1] https://eprint.iacr.org/2003/191
2117 * [2] https://eprint.iacr.org/2020/055
2119 * Avoid the leak by randomizing coordinates before we normalize them.
2121 #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2122 if (f_rng != 0)
2123 #endif
2124 MBEDTLS_MPI_CHK(ecp_randomize_jac(grp, RR, f_rng, p_rng));
2126 MBEDTLS_MPI_CHK(ecp_normalize_jac(grp, RR));
2128 #if defined(MBEDTLS_ECP_RESTARTABLE)
2129 if (rs_ctx != NULL && rs_ctx->rsm != NULL)
2130 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, RR));
2131 #endif
2133 cleanup:
2134 return (ret);
2138 * Pick window size based on curve size and whether we optimize for base point
2140 static unsigned char ecp_pick_window_size(const mbedtls_ecp_group *grp,
2141 unsigned char p_eq_g) {
2142 unsigned char w;
2145 * Minimize the number of multiplications, that is minimize
2146 * 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w )
2147 * (see costs of the various parts, with 1S = 1M)
2149 w = grp->nbits >= 384 ? 5 : 4;
2152 * If P == G, pre-compute a bit more, since this may be re-used later.
2153 * Just adding one avoids upping the cost of the first mul too much,
2154 * and the memory cost too.
2156 if (p_eq_g)
2157 w++;
2160 * Make sure w is within bounds.
2161 * (The last test is useful only for very small curves in the test suite.)
2163 #if( MBEDTLS_ECP_WINDOW_SIZE < 6 )
2164 if (w > MBEDTLS_ECP_WINDOW_SIZE)
2165 w = MBEDTLS_ECP_WINDOW_SIZE;
2166 #endif
2167 if (w >= grp->nbits)
2168 w = 2;
2170 return (w);
2174 * Multiplication using the comb method - for curves in short Weierstrass form
2176 * This function is mainly responsible for administrative work:
2177 * - managing the restart context if enabled
2178 * - managing the table of precomputed points (passed between the below two
2179 * functions): allocation, computation, ownership tranfer, freeing.
2181 * It delegates the actual arithmetic work to:
2182 * ecp_precompute_comb() and ecp_mul_comb_with_precomp()
2184 * See comments on ecp_comb_recode_core() regarding the computation strategy.
2186 static int ecp_mul_comb(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2187 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2188 int (*f_rng)(void *, unsigned char *, size_t),
2189 void *p_rng,
2190 mbedtls_ecp_restart_ctx *rs_ctx) {
2191 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2192 unsigned char w, p_eq_g, i;
2193 size_t d;
2194 unsigned char T_size = 0, T_ok = 0;
2195 mbedtls_ecp_point *T = NULL;
2196 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2197 ecp_drbg_context drbg_ctx;
2199 ecp_drbg_init(&drbg_ctx);
2200 #endif
2202 ECP_RS_ENTER(rsm);
2204 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2205 if (f_rng == NULL) {
2206 /* Adjust pointers */
2207 f_rng = &ecp_drbg_random;
2208 #if defined(MBEDTLS_ECP_RESTARTABLE)
2209 if (rs_ctx != NULL && rs_ctx->rsm != NULL)
2210 p_rng = &rs_ctx->rsm->drbg_ctx;
2211 else
2212 #endif
2213 p_rng = &drbg_ctx;
2215 /* Initialize internal DRBG if necessary */
2216 #if defined(MBEDTLS_ECP_RESTARTABLE)
2217 if (rs_ctx == NULL || rs_ctx->rsm == NULL ||
2218 rs_ctx->rsm->drbg_seeded == 0)
2219 #endif
2221 const size_t m_len = (grp->nbits + 7) / 8;
2222 MBEDTLS_MPI_CHK(ecp_drbg_seed(p_rng, m, m_len));
2224 #if defined(MBEDTLS_ECP_RESTARTABLE)
2225 if (rs_ctx != NULL && rs_ctx->rsm != NULL)
2226 rs_ctx->rsm->drbg_seeded = 1;
2227 #endif
2229 #endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */
2231 /* Is P the base point ? */
2232 #if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
2233 p_eq_g = (mbedtls_mpi_cmp_mpi(&P->Y, &grp->G.Y) == 0 &&
2234 mbedtls_mpi_cmp_mpi(&P->X, &grp->G.X) == 0);
2235 #else
2236 p_eq_g = 0;
2237 #endif
2239 /* Pick window size and deduce related sizes */
2240 w = ecp_pick_window_size(grp, p_eq_g);
2241 T_size = 1U << (w - 1);
2242 d = (grp->nbits + w - 1) / w;
2244 /* Pre-computed table: do we have it already for the base point? */
2245 if (p_eq_g && grp->T != NULL) {
2246 /* second pointer to the same table, will be deleted on exit */
2247 T = grp->T;
2248 T_ok = 1;
2249 } else
2250 #if defined(MBEDTLS_ECP_RESTARTABLE)
2251 /* Pre-computed table: do we have one in progress? complete? */
2252 if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->T != NULL) {
2253 /* transfer ownership of T from rsm to local function */
2254 T = rs_ctx->rsm->T;
2255 rs_ctx->rsm->T = NULL;
2256 rs_ctx->rsm->T_size = 0;
2258 /* This effectively jumps to the call to mul_comb_after_precomp() */
2259 T_ok = rs_ctx->rsm->state >= ecp_rsm_comb_core;
2260 } else
2261 #endif
2262 /* Allocate table if we didn't have any */
2264 T = mbedtls_calloc(T_size, sizeof(mbedtls_ecp_point));
2265 if (T == NULL) {
2266 ret = MBEDTLS_ERR_ECP_ALLOC_FAILED;
2267 goto cleanup;
2270 for (i = 0; i < T_size; i++)
2271 mbedtls_ecp_point_init(&T[i]);
2273 T_ok = 0;
2276 /* Compute table (or finish computing it) if not done already */
2277 if (!T_ok) {
2278 MBEDTLS_MPI_CHK(ecp_precompute_comb(grp, T, P, w, d, rs_ctx));
2280 if (p_eq_g) {
2281 /* almost transfer ownership of T to the group, but keep a copy of
2282 * the pointer to use for calling the next function more easily */
2283 grp->T = T;
2284 grp->T_size = T_size;
2288 /* Actual comb multiplication using precomputed points */
2289 MBEDTLS_MPI_CHK(ecp_mul_comb_after_precomp(grp, R, m,
2290 T, T_size, w, d,
2291 f_rng, p_rng, rs_ctx));
2293 cleanup:
2295 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2296 ecp_drbg_free(&drbg_ctx);
2297 #endif
2299 /* does T belong to the group? */
2300 if (T == grp->T)
2301 T = NULL;
2303 /* does T belong to the restart context? */
2304 #if defined(MBEDTLS_ECP_RESTARTABLE)
2305 if (rs_ctx != NULL && rs_ctx->rsm != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS && T != NULL) {
2306 /* transfer ownership of T from local function to rsm */
2307 rs_ctx->rsm->T_size = T_size;
2308 rs_ctx->rsm->T = T;
2309 T = NULL;
2311 #endif
2313 /* did T belong to us? then let's destroy it! */
2314 if (T != NULL) {
2315 for (i = 0; i < T_size; i++)
2316 mbedtls_ecp_point_free(&T[i]);
2317 mbedtls_free(T);
2320 /* don't free R while in progress in case R == P */
2321 #if defined(MBEDTLS_ECP_RESTARTABLE)
2322 if (ret != MBEDTLS_ERR_ECP_IN_PROGRESS)
2323 #endif
2324 /* prevent caller from using invalid value */
2325 if (ret != 0)
2326 mbedtls_ecp_point_free(R);
2328 ECP_RS_LEAVE(rsm);
2330 return (ret);
2333 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2335 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2337 * For Montgomery curves, we do all the internal arithmetic in projective
2338 * coordinates. Import/export of points uses only the x coordinates, which is
2339 * internaly represented as X / Z.
2341 * For scalar multiplication, we'll use a Montgomery ladder.
2345 * Normalize Montgomery x/z coordinates: X = X/Z, Z = 1
2346 * Cost: 1M + 1I
2348 static int ecp_normalize_mxz(const mbedtls_ecp_group *grp, mbedtls_ecp_point *P) {
2349 #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
2350 if (mbedtls_internal_ecp_grp_capable(grp))
2351 return (mbedtls_internal_ecp_normalize_mxz(grp, P));
2352 #endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */
2354 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
2355 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
2356 #else
2357 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2358 MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&P->Z, &P->Z, &grp->P));
2359 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &P->X, &P->X, &P->Z));
2360 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&P->Z, 1));
2362 cleanup:
2363 return (ret);
2364 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) */
2368 * Randomize projective x/z coordinates:
2369 * (X, Z) -> (l X, l Z) for random l
2370 * This is sort of the reverse operation of ecp_normalize_mxz().
2372 * This countermeasure was first suggested in [2].
2373 * Cost: 2M
2375 static int ecp_randomize_mxz(const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,
2376 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) {
2377 #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
2378 if (mbedtls_internal_ecp_grp_capable(grp))
2379 return (mbedtls_internal_ecp_randomize_mxz(grp, P, f_rng, p_rng);
2380 #endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */
2382 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
2383 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
2384 #else
2385 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2386 mbedtls_mpi l;
2387 int count = 0;
2388 size_t p_size = (grp->pbits + 7) / 8;
2389 mbedtls_mpi_init(&l);
2391 /* Generate l such that 1 < l < p */
2392 do {
2393 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&l, p_size, f_rng, p_rng));
2395 while (mbedtls_mpi_cmp_mpi(&l, &grp->P) >= 0)
2396 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&l, 1));
2398 if (count++ > 10) {
2399 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
2400 goto cleanup;
2402 } while (mbedtls_mpi_cmp_int(&l, 1) <= 0);
2404 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &P->X, &P->X, &l));
2405 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &P->Z, &P->Z, &l));
2407 cleanup:
2408 mbedtls_mpi_free(&l);
2410 return (ret);
2411 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) */
2415 * Double-and-add: R = 2P, S = P + Q, with d = X(P - Q),
2416 * for Montgomery curves in x/z coordinates.
2418 * http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3
2419 * with
2420 * d = X1
2421 * P = (X2, Z2)
2422 * Q = (X3, Z3)
2423 * R = (X4, Z4)
2424 * S = (X5, Z5)
2425 * and eliminating temporary variables tO, ..., t4.
2427 * Cost: 5M + 4S
2429 static int ecp_double_add_mxz(const mbedtls_ecp_group *grp,
2430 mbedtls_ecp_point *R, mbedtls_ecp_point *S,
2431 const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
2432 const mbedtls_mpi *d) {
2433 #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
2434 if (mbedtls_internal_ecp_grp_capable(grp))
2435 return (mbedtls_internal_ecp_double_add_mxz(grp, R, S, P, Q, d));
2436 #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */
2438 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
2439 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
2440 #else
2441 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2442 mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB;
2444 mbedtls_mpi_init(&A);
2445 mbedtls_mpi_init(&AA);
2446 mbedtls_mpi_init(&B);
2447 mbedtls_mpi_init(&BB);
2448 mbedtls_mpi_init(&E);
2449 mbedtls_mpi_init(&C);
2450 mbedtls_mpi_init(&D);
2451 mbedtls_mpi_init(&DA);
2452 mbedtls_mpi_init(&CB);
2454 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &A, &P->X, &P->Z));
2455 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &AA, &A, &A));
2456 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &B, &P->X, &P->Z));
2457 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &BB, &B, &B));
2458 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &E, &AA, &BB));
2459 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &C, &Q->X, &Q->Z));
2460 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &D, &Q->X, &Q->Z));
2461 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &DA, &D, &A));
2462 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &CB, &C, &B));
2463 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &S->X, &DA, &CB));
2464 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S->X, &S->X, &S->X));
2465 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, &S->Z, &DA, &CB));
2466 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S->Z, &S->Z, &S->Z));
2467 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &S->Z, d, &S->Z));
2468 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &R->X, &AA, &BB));
2469 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &R->Z, &grp->A, &E));
2470 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &R->Z, &BB, &R->Z));
2471 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &R->Z, &E, &R->Z));
2473 cleanup:
2474 mbedtls_mpi_free(&A);
2475 mbedtls_mpi_free(&AA);
2476 mbedtls_mpi_free(&B);
2477 mbedtls_mpi_free(&BB);
2478 mbedtls_mpi_free(&E);
2479 mbedtls_mpi_free(&C);
2480 mbedtls_mpi_free(&D);
2481 mbedtls_mpi_free(&DA);
2482 mbedtls_mpi_free(&CB);
2484 return (ret);
2485 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) */
2489 * Multiplication with Montgomery ladder in x/z coordinates,
2490 * for curves in Montgomery form
2492 static int ecp_mul_mxz(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2493 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2494 int (*f_rng)(void *, unsigned char *, size_t),
2495 void *p_rng) {
2496 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2497 size_t i;
2498 unsigned char b;
2499 mbedtls_ecp_point RP;
2500 mbedtls_mpi PX;
2501 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2502 ecp_drbg_context drbg_ctx;
2504 ecp_drbg_init(&drbg_ctx);
2505 #endif
2506 mbedtls_ecp_point_init(&RP);
2507 mbedtls_mpi_init(&PX);
2509 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2510 if (f_rng == NULL) {
2511 const size_t m_len = (grp->nbits + 7) / 8;
2512 MBEDTLS_MPI_CHK(ecp_drbg_seed(&drbg_ctx, m, m_len));
2513 f_rng = &ecp_drbg_random;
2514 p_rng = &drbg_ctx;
2516 #endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */
2518 /* Save PX and read from P before writing to R, in case P == R */
2519 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&PX, &P->X));
2520 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(&RP, P));
2522 /* Set R to zero in modified x/z coordinates */
2523 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->X, 1));
2524 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 0));
2525 mbedtls_mpi_free(&R->Y);
2527 /* RP.X might be sligtly larger than P, so reduce it */
2528 MOD_ADD(RP.X);
2530 /* Randomize coordinates of the starting point */
2531 #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2532 if (f_rng != NULL)
2533 #endif
2534 MBEDTLS_MPI_CHK(ecp_randomize_mxz(grp, &RP, f_rng, p_rng));
2536 /* Loop invariant: R = result so far, RP = R + P */
2537 i = mbedtls_mpi_bitlen(m); /* one past the (zero-based) most significant bit */
2538 while (i-- > 0) {
2539 b = mbedtls_mpi_get_bit(m, i);
2541 * if (b) R = 2R + P else R = 2R,
2542 * which is:
2543 * if (b) double_add( RP, R, RP, R )
2544 * else double_add( R, RP, R, RP )
2545 * but using safe conditional swaps to avoid leaks
2547 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_swap(&R->X, &RP.X, b));
2548 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_swap(&R->Z, &RP.Z, b));
2549 MBEDTLS_MPI_CHK(ecp_double_add_mxz(grp, R, &RP, R, &RP, &PX));
2550 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_swap(&R->X, &RP.X, b));
2551 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_swap(&R->Z, &RP.Z, b));
2555 * Knowledge of the projective coordinates may leak the last few bits of the
2556 * scalar [1], and since our MPI implementation isn't constant-flow,
2557 * inversion (used for coordinate normalization) may leak the full value
2558 * of its input via side-channels [2].
2560 * [1] https://eprint.iacr.org/2003/191
2561 * [2] https://eprint.iacr.org/2020/055
2563 * Avoid the leak by randomizing coordinates before we normalize them.
2565 #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2566 if (f_rng != NULL)
2567 #endif
2568 MBEDTLS_MPI_CHK(ecp_randomize_mxz(grp, R, f_rng, p_rng));
2570 MBEDTLS_MPI_CHK(ecp_normalize_mxz(grp, R));
2572 cleanup:
2573 #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
2574 ecp_drbg_free(&drbg_ctx);
2575 #endif
2577 mbedtls_ecp_point_free(&RP);
2578 mbedtls_mpi_free(&PX);
2580 return (ret);
2583 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2586 * Restartable multiplication R = m * P
2588 int mbedtls_ecp_mul_restartable(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2589 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2590 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
2591 mbedtls_ecp_restart_ctx *rs_ctx) {
2592 int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2593 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2594 char is_grp_capable = 0;
2595 #endif
2596 ECP_VALIDATE_RET(grp != NULL);
2597 ECP_VALIDATE_RET(R != NULL);
2598 ECP_VALIDATE_RET(m != NULL);
2599 ECP_VALIDATE_RET(P != NULL);
2601 #if defined(MBEDTLS_ECP_RESTARTABLE)
2602 /* reset ops count for this call if top-level */
2603 if (rs_ctx != NULL && rs_ctx->depth++ == 0)
2604 rs_ctx->ops_done = 0;
2605 #else
2606 (void) rs_ctx;
2607 #endif
2609 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2610 if ((is_grp_capable = mbedtls_internal_ecp_grp_capable(grp)))
2611 MBEDTLS_MPI_CHK(mbedtls_internal_ecp_init(grp));
2612 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2614 #if defined(MBEDTLS_ECP_RESTARTABLE)
2615 /* skip argument check when restarting */
2616 if (rs_ctx == NULL || rs_ctx->rsm == NULL)
2617 #endif
2619 /* check_privkey is free */
2620 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_CHK);
2622 /* Common sanity checks */
2623 MBEDTLS_MPI_CHK(mbedtls_ecp_check_privkey(grp, m));
2624 MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
2627 ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2628 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2629 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY)
2630 MBEDTLS_MPI_CHK(ecp_mul_mxz(grp, R, m, P, f_rng, p_rng));
2631 #endif
2632 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2633 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS)
2634 MBEDTLS_MPI_CHK(ecp_mul_comb(grp, R, m, P, f_rng, p_rng, rs_ctx));
2635 #endif
2637 cleanup:
2639 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2640 if (is_grp_capable)
2641 mbedtls_internal_ecp_free(grp);
2642 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2644 #if defined(MBEDTLS_ECP_RESTARTABLE)
2645 if (rs_ctx != NULL)
2646 rs_ctx->depth--;
2647 #endif
2649 return (ret);
2653 * Multiplication R = m * P
2655 int mbedtls_ecp_mul(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2656 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2657 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) {
2658 ECP_VALIDATE_RET(grp != NULL);
2659 ECP_VALIDATE_RET(R != NULL);
2660 ECP_VALIDATE_RET(m != NULL);
2661 ECP_VALIDATE_RET(P != NULL);
2662 return (mbedtls_ecp_mul_restartable(grp, R, m, P, f_rng, p_rng, NULL));
2665 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2667 * Check that an affine point is valid as a public key,
2668 * short weierstrass curves (SEC1 3.2.3.1)
2670 static int ecp_check_pubkey_sw(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt) {
2671 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2672 mbedtls_mpi YY, RHS;
2674 /* pt coordinates must be normalized for our checks */
2675 if (mbedtls_mpi_cmp_int(&pt->X, 0) < 0 ||
2676 mbedtls_mpi_cmp_int(&pt->Y, 0) < 0 ||
2677 mbedtls_mpi_cmp_mpi(&pt->X, &grp->P) >= 0 ||
2678 mbedtls_mpi_cmp_mpi(&pt->Y, &grp->P) >= 0)
2679 return (MBEDTLS_ERR_ECP_INVALID_KEY);
2681 mbedtls_mpi_init(&YY);
2682 mbedtls_mpi_init(&RHS);
2685 * YY = Y^2
2686 * RHS = X (X^2 + A) + B = X^3 + A X + B
2688 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &YY, &pt->Y, &pt->Y));
2689 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &RHS, &pt->X, &pt->X));
2691 /* Special case for A = -3 */
2692 if (grp->A.p == NULL) {
2693 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&RHS, &RHS, 3));
2694 MOD_SUB(RHS);
2695 } else {
2696 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &RHS, &RHS, &grp->A));
2699 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, &RHS, &RHS, &pt->X));
2700 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, &RHS, &RHS, &grp->B));
2702 if (mbedtls_mpi_cmp_mpi(&YY, &RHS) != 0)
2703 ret = MBEDTLS_ERR_ECP_INVALID_KEY;
2705 cleanup:
2707 mbedtls_mpi_free(&YY);
2708 mbedtls_mpi_free(&RHS);
2710 return (ret);
2712 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2714 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2716 * R = m * P with shortcuts for m == 1 and m == -1
2717 * NOT constant-time - ONLY for short Weierstrass!
2719 static int mbedtls_ecp_mul_shortcuts(mbedtls_ecp_group *grp,
2720 mbedtls_ecp_point *R,
2721 const mbedtls_mpi *m,
2722 const mbedtls_ecp_point *P,
2723 mbedtls_ecp_restart_ctx *rs_ctx) {
2724 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2726 if (mbedtls_mpi_cmp_int(m, 1) == 0) {
2727 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, P));
2728 } else if (mbedtls_mpi_cmp_int(m, -1) == 0) {
2729 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, P));
2730 if (mbedtls_mpi_cmp_int(&R->Y, 0) != 0)
2731 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&R->Y, &grp->P, &R->Y));
2732 } else {
2733 MBEDTLS_MPI_CHK(mbedtls_ecp_mul_restartable(grp, R, m, P,
2734 NULL, NULL, rs_ctx));
2737 cleanup:
2738 return (ret);
2742 * Restartable linear combination
2743 * NOT constant-time
2745 int mbedtls_ecp_muladd_restartable(
2746 mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2747 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2748 const mbedtls_mpi *n, const mbedtls_ecp_point *Q,
2749 mbedtls_ecp_restart_ctx *rs_ctx) {
2750 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2751 mbedtls_ecp_point mP;
2752 mbedtls_ecp_point *pmP = &mP;
2753 mbedtls_ecp_point *pR = R;
2754 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2755 char is_grp_capable = 0;
2756 #endif
2757 ECP_VALIDATE_RET(grp != NULL);
2758 ECP_VALIDATE_RET(R != NULL);
2759 ECP_VALIDATE_RET(m != NULL);
2760 ECP_VALIDATE_RET(P != NULL);
2761 ECP_VALIDATE_RET(n != NULL);
2762 ECP_VALIDATE_RET(Q != NULL);
2764 if (mbedtls_ecp_get_type(grp) != MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS)
2765 return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE);
2767 mbedtls_ecp_point_init(&mP);
2769 ECP_RS_ENTER(ma);
2771 #if defined(MBEDTLS_ECP_RESTARTABLE)
2772 if (rs_ctx != NULL && rs_ctx->ma != NULL) {
2773 /* redirect intermediate results to restart context */
2774 pmP = &rs_ctx->ma->mP;
2775 pR = &rs_ctx->ma->R;
2777 /* jump to next operation */
2778 if (rs_ctx->ma->state == ecp_rsma_mul2)
2779 goto mul2;
2780 if (rs_ctx->ma->state == ecp_rsma_add)
2781 goto add;
2782 if (rs_ctx->ma->state == ecp_rsma_norm)
2783 goto norm;
2785 #endif /* MBEDTLS_ECP_RESTARTABLE */
2787 MBEDTLS_MPI_CHK(mbedtls_ecp_mul_shortcuts(grp, pmP, m, P, rs_ctx));
2788 #if defined(MBEDTLS_ECP_RESTARTABLE)
2789 if (rs_ctx != NULL && rs_ctx->ma != NULL)
2790 rs_ctx->ma->state = ecp_rsma_mul2;
2792 mul2:
2793 #endif
2794 MBEDTLS_MPI_CHK(mbedtls_ecp_mul_shortcuts(grp, pR, n, Q, rs_ctx));
2796 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2797 if ((is_grp_capable = mbedtls_internal_ecp_grp_capable(grp)))
2798 MBEDTLS_MPI_CHK(mbedtls_internal_ecp_init(grp));
2799 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2801 #if defined(MBEDTLS_ECP_RESTARTABLE)
2802 if (rs_ctx != NULL && rs_ctx->ma != NULL)
2803 rs_ctx->ma->state = ecp_rsma_add;
2805 add:
2806 #endif
2807 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_ADD);
2808 MBEDTLS_MPI_CHK(ecp_add_mixed(grp, pR, pmP, pR));
2809 #if defined(MBEDTLS_ECP_RESTARTABLE)
2810 if (rs_ctx != NULL && rs_ctx->ma != NULL)
2811 rs_ctx->ma->state = ecp_rsma_norm;
2813 norm:
2814 #endif
2815 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV);
2816 MBEDTLS_MPI_CHK(ecp_normalize_jac(grp, pR));
2818 #if defined(MBEDTLS_ECP_RESTARTABLE)
2819 if (rs_ctx != NULL && rs_ctx->ma != NULL)
2820 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, pR));
2821 #endif
2823 cleanup:
2824 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2825 if (is_grp_capable)
2826 mbedtls_internal_ecp_free(grp);
2827 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2829 mbedtls_ecp_point_free(&mP);
2831 ECP_RS_LEAVE(ma);
2833 return (ret);
2837 * Linear combination
2838 * NOT constant-time
2840 int mbedtls_ecp_muladd(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2841 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2842 const mbedtls_mpi *n, const mbedtls_ecp_point *Q) {
2843 ECP_VALIDATE_RET(grp != NULL);
2844 ECP_VALIDATE_RET(R != NULL);
2845 ECP_VALIDATE_RET(m != NULL);
2846 ECP_VALIDATE_RET(P != NULL);
2847 ECP_VALIDATE_RET(n != NULL);
2848 ECP_VALIDATE_RET(Q != NULL);
2849 return (mbedtls_ecp_muladd_restartable(grp, R, m, P, n, Q, NULL));
2851 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2853 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2855 * Check validity of a public key for Montgomery curves with x-only schemes
2857 static int ecp_check_pubkey_mx(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt) {
2858 /* [Curve25519 p. 5] Just check X is the correct number of bytes */
2859 /* Allow any public value, if it's too big then we'll just reduce it mod p
2860 * (RFC 7748 sec. 5 para. 3). */
2861 if (mbedtls_mpi_size(&pt->X) > (grp->nbits + 7) / 8)
2862 return (MBEDTLS_ERR_ECP_INVALID_KEY);
2864 return (0);
2866 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2869 * Check that a point is valid as a public key
2871 int mbedtls_ecp_check_pubkey(const mbedtls_ecp_group *grp,
2872 const mbedtls_ecp_point *pt) {
2873 ECP_VALIDATE_RET(grp != NULL);
2874 ECP_VALIDATE_RET(pt != NULL);
2876 /* Must use affine coordinates */
2877 if (mbedtls_mpi_cmp_int(&pt->Z, 1) != 0)
2878 return (MBEDTLS_ERR_ECP_INVALID_KEY);
2880 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2881 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY)
2882 return (ecp_check_pubkey_mx(grp, pt));
2883 #endif
2884 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2885 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS)
2886 return (ecp_check_pubkey_sw(grp, pt));
2887 #endif
2888 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
2892 * Check that an mbedtls_mpi is valid as a private key
2894 int mbedtls_ecp_check_privkey(const mbedtls_ecp_group *grp,
2895 const mbedtls_mpi *d) {
2896 ECP_VALIDATE_RET(grp != NULL);
2897 ECP_VALIDATE_RET(d != NULL);
2899 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2900 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
2901 /* see RFC 7748 sec. 5 para. 5 */
2902 if (mbedtls_mpi_get_bit(d, 0) != 0 ||
2903 mbedtls_mpi_get_bit(d, 1) != 0 ||
2904 mbedtls_mpi_bitlen(d) - 1 != grp->nbits) /* mbedtls_mpi_bitlen is one-based! */
2905 return (MBEDTLS_ERR_ECP_INVALID_KEY);
2907 /* see [Curve25519] page 5 */
2908 if (grp->nbits == 254 && mbedtls_mpi_get_bit(d, 2) != 0)
2909 return (MBEDTLS_ERR_ECP_INVALID_KEY);
2911 return (0);
2913 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2914 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2915 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
2916 /* see SEC1 3.2 */
2917 if (mbedtls_mpi_cmp_int(d, 1) < 0 ||
2918 mbedtls_mpi_cmp_mpi(d, &grp->N) >= 0)
2919 return (MBEDTLS_ERR_ECP_INVALID_KEY);
2920 else
2921 return (0);
2923 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2925 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
2929 * Generate a private key
2931 int mbedtls_ecp_gen_privkey(const mbedtls_ecp_group *grp,
2932 mbedtls_mpi *d,
2933 int (*f_rng)(void *, unsigned char *, size_t),
2934 void *p_rng) {
2935 int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2936 size_t n_size;
2938 ECP_VALIDATE_RET(grp != NULL);
2939 ECP_VALIDATE_RET(d != NULL);
2940 ECP_VALIDATE_RET(f_rng != NULL);
2942 n_size = (grp->nbits + 7) / 8;
2944 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2945 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
2946 /* [M225] page 5 */
2947 size_t b;
2949 do {
2950 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(d, n_size, f_rng, p_rng));
2951 } while (mbedtls_mpi_bitlen(d) == 0);
2953 /* Make sure the most significant bit is nbits */
2954 b = mbedtls_mpi_bitlen(d) - 1; /* mbedtls_mpi_bitlen is one-based */
2955 if (b > grp->nbits)
2956 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(d, b - grp->nbits));
2957 else
2958 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, grp->nbits, 1));
2960 /* Make sure the last two bits are unset for Curve448, three bits for
2961 Curve25519 */
2962 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 0, 0));
2963 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 1, 0));
2964 if (grp->nbits == 254) {
2965 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 2, 0));
2968 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2970 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2971 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
2972 /* SEC1 3.2.1: Generate d such that 1 <= n < N */
2973 int count = 0;
2974 unsigned cmp = 0;
2977 * Match the procedure given in RFC 6979 (deterministic ECDSA):
2978 * - use the same byte ordering;
2979 * - keep the leftmost nbits bits of the generated octet string;
2980 * - try until result is in the desired range.
2981 * This also avoids any biais, which is especially important for ECDSA.
2983 do {
2984 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(d, n_size, f_rng, p_rng));
2985 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(d, 8 * n_size - grp->nbits));
2988 * Each try has at worst a probability 1/2 of failing (the msb has
2989 * a probability 1/2 of being 0, and then the result will be < N),
2990 * so after 30 tries failure probability is a most 2**(-30).
2992 * For most curves, 1 try is enough with overwhelming probability,
2993 * since N starts with a lot of 1s in binary, but some curves
2994 * such as secp224k1 are actually very close to the worst case.
2996 if (++count > 30) {
2997 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
2998 goto cleanup;
3001 ret = mbedtls_mpi_lt_mpi_ct(d, &grp->N, &cmp);
3002 if (ret != 0) {
3003 goto cleanup;
3005 } while (mbedtls_mpi_cmp_int(d, 1) < 0 || cmp != 1);
3007 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3009 cleanup:
3010 return (ret);
3014 * Generate a keypair with configurable base point
3016 int mbedtls_ecp_gen_keypair_base(mbedtls_ecp_group *grp,
3017 const mbedtls_ecp_point *G,
3018 mbedtls_mpi *d, mbedtls_ecp_point *Q,
3019 int (*f_rng)(void *, unsigned char *, size_t),
3020 void *p_rng) {
3021 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3022 ECP_VALIDATE_RET(grp != NULL);
3023 ECP_VALIDATE_RET(d != NULL);
3024 ECP_VALIDATE_RET(G != NULL);
3025 ECP_VALIDATE_RET(Q != NULL);
3026 ECP_VALIDATE_RET(f_rng != NULL);
3028 MBEDTLS_MPI_CHK(mbedtls_ecp_gen_privkey(grp, d, f_rng, p_rng));
3029 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, Q, d, G, f_rng, p_rng));
3031 cleanup:
3032 return (ret);
3036 * Generate key pair, wrapper for conventional base point
3038 int mbedtls_ecp_gen_keypair(mbedtls_ecp_group *grp,
3039 mbedtls_mpi *d, mbedtls_ecp_point *Q,
3040 int (*f_rng)(void *, unsigned char *, size_t),
3041 void *p_rng) {
3042 ECP_VALIDATE_RET(grp != NULL);
3043 ECP_VALIDATE_RET(d != NULL);
3044 ECP_VALIDATE_RET(Q != NULL);
3045 ECP_VALIDATE_RET(f_rng != NULL);
3047 return (mbedtls_ecp_gen_keypair_base(grp, &grp->G, d, Q, f_rng, p_rng));
3051 * Generate a keypair, prettier wrapper
3053 int mbedtls_ecp_gen_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
3054 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) {
3055 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3056 ECP_VALIDATE_RET(key != NULL);
3057 ECP_VALIDATE_RET(f_rng != NULL);
3059 if ((ret = mbedtls_ecp_group_load(&key->grp, grp_id)) != 0)
3060 return (ret);
3062 return (mbedtls_ecp_gen_keypair(&key->grp, &key->d, &key->Q, f_rng, p_rng));
3065 #define ECP_CURVE25519_KEY_SIZE 32
3067 * Read a private key.
3069 int mbedtls_ecp_read_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
3070 const unsigned char *buf, size_t buflen) {
3071 int ret = 0;
3073 ECP_VALIDATE_RET(key != NULL);
3074 ECP_VALIDATE_RET(buf != NULL);
3076 if ((ret = mbedtls_ecp_group_load(&key->grp, grp_id)) != 0)
3077 return (ret);
3079 ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
3081 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3082 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3084 * If it is Curve25519 curve then mask the key as mandated by RFC7748
3086 if (grp_id == MBEDTLS_ECP_DP_CURVE25519) {
3087 if (buflen != ECP_CURVE25519_KEY_SIZE)
3088 return MBEDTLS_ERR_ECP_INVALID_KEY;
3090 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&key->d, buf, buflen));
3092 /* Set the three least significant bits to 0 */
3093 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 0, 0));
3094 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 1, 0));
3095 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 2, 0));
3097 /* Set the most significant bit to 0 */
3098 MBEDTLS_MPI_CHK(
3099 mbedtls_mpi_set_bit(&key->d,
3100 ECP_CURVE25519_KEY_SIZE * 8 - 1, 0)
3103 /* Set the second most significant bit to 1 */
3104 MBEDTLS_MPI_CHK(
3105 mbedtls_mpi_set_bit(&key->d,
3106 ECP_CURVE25519_KEY_SIZE * 8 - 2, 1)
3108 } else
3109 ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
3112 #endif
3113 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3114 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3115 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&key->d, buf, buflen));
3117 MBEDTLS_MPI_CHK(mbedtls_ecp_check_privkey(&key->grp, &key->d));
3120 #endif
3121 cleanup:
3123 if (ret != 0)
3124 mbedtls_mpi_free(&key->d);
3126 return (ret);
3130 * Write a private key.
3132 int mbedtls_ecp_write_key(mbedtls_ecp_keypair *key,
3133 unsigned char *buf, size_t buflen) {
3134 int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
3136 ECP_VALIDATE_RET(key != NULL);
3137 ECP_VALIDATE_RET(buf != NULL);
3139 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3140 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3141 if (key->grp.id == MBEDTLS_ECP_DP_CURVE25519) {
3142 if (buflen < ECP_CURVE25519_KEY_SIZE)
3143 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
3145 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary_le(&key->d, buf, buflen));
3146 } else
3147 ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
3150 #endif
3151 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3152 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3153 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&key->d, buf, buflen));
3156 #endif
3157 cleanup:
3159 return (ret);
3164 * Check a public-private key pair
3166 int mbedtls_ecp_check_pub_priv(const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv) {
3167 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3168 mbedtls_ecp_point Q;
3169 mbedtls_ecp_group grp;
3170 ECP_VALIDATE_RET(pub != NULL);
3171 ECP_VALIDATE_RET(prv != NULL);
3173 if (pub->grp.id == MBEDTLS_ECP_DP_NONE ||
3174 pub->grp.id != prv->grp.id ||
3175 mbedtls_mpi_cmp_mpi(&pub->Q.X, &prv->Q.X) ||
3176 mbedtls_mpi_cmp_mpi(&pub->Q.Y, &prv->Q.Y) ||
3177 mbedtls_mpi_cmp_mpi(&pub->Q.Z, &prv->Q.Z)) {
3178 return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
3181 mbedtls_ecp_point_init(&Q);
3182 mbedtls_ecp_group_init(&grp);
3184 /* mbedtls_ecp_mul() needs a non-const group... */
3185 mbedtls_ecp_group_copy(&grp, &prv->grp);
3187 /* Also checks d is valid */
3188 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(&grp, &Q, &prv->d, &prv->grp.G, NULL, NULL));
3190 if (mbedtls_mpi_cmp_mpi(&Q.X, &prv->Q.X) ||
3191 mbedtls_mpi_cmp_mpi(&Q.Y, &prv->Q.Y) ||
3192 mbedtls_mpi_cmp_mpi(&Q.Z, &prv->Q.Z)) {
3193 ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3194 goto cleanup;
3197 cleanup:
3198 mbedtls_ecp_point_free(&Q);
3199 mbedtls_ecp_group_free(&grp);
3201 return (ret);
3204 #if defined(MBEDTLS_SELF_TEST)
3206 /* Adjust the exponent to be a valid private point for the specified curve.
3207 * This is sometimes necessary because we use a single set of exponents
3208 * for all curves but the validity of values depends on the curve. */
3209 static int self_test_adjust_exponent(const mbedtls_ecp_group *grp,
3210 mbedtls_mpi *m) {
3211 int ret = 0;
3212 switch (grp->id) {
3213 /* If Curve25519 is available, then that's what we use for the
3214 * Montgomery test, so we don't need the adjustment code. */
3215 #if ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
3216 #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
3217 case MBEDTLS_ECP_DP_CURVE448:
3218 /* Move highest bit from 254 to N-1. Setting bit N-1 is
3219 * necessary to enforce the highest-bit-set constraint. */
3220 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(m, 254, 0));
3221 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(m, grp->nbits, 1));
3222 /* Copy second-highest bit from 253 to N-2. This is not
3223 * necessary but improves the test variety a bit. */
3224 MBEDTLS_MPI_CHK(
3225 mbedtls_mpi_set_bit(m, grp->nbits - 1,
3226 mbedtls_mpi_get_bit(m, 253)));
3227 break;
3228 #endif
3229 #endif /* ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) */
3230 default:
3231 /* Non-Montgomery curves and Curve25519 need no adjustment. */
3232 (void) grp;
3233 (void) m;
3234 goto cleanup;
3236 cleanup:
3237 return (ret);
3240 /* Calculate R = m.P for each m in exponents. Check that the number of
3241 * basic operations doesn't depend on the value of m. */
3242 static int self_test_point(int verbose,
3243 mbedtls_ecp_group *grp,
3244 mbedtls_ecp_point *R,
3245 mbedtls_mpi *m,
3246 const mbedtls_ecp_point *P,
3247 const char *const *exponents,
3248 size_t n_exponents) {
3249 int ret = 0;
3250 size_t i = 0;
3251 unsigned long add_c_prev, dbl_c_prev, mul_c_prev;
3252 add_count = 0;
3253 dbl_count = 0;
3254 mul_count = 0;
3256 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(m, 16, exponents[0]));
3257 MBEDTLS_MPI_CHK(self_test_adjust_exponent(grp, m));
3258 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, R, m, P, NULL, NULL));
3260 for (i = 1; i < n_exponents; i++) {
3261 add_c_prev = add_count;
3262 dbl_c_prev = dbl_count;
3263 mul_c_prev = mul_count;
3264 add_count = 0;
3265 dbl_count = 0;
3266 mul_count = 0;
3268 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(m, 16, exponents[i]));
3269 MBEDTLS_MPI_CHK(self_test_adjust_exponent(grp, m));
3270 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, R, m, P, NULL, NULL));
3272 if (add_count != add_c_prev ||
3273 dbl_count != dbl_c_prev ||
3274 mul_count != mul_c_prev) {
3275 ret = 1;
3276 break;
3280 cleanup:
3281 if (verbose != 0) {
3282 if (ret != 0)
3283 mbedtls_printf("failed (%u)\n", (unsigned int) i);
3284 else
3285 mbedtls_printf("passed\n");
3287 return (ret);
3291 * Checkup routine
3293 int mbedtls_ecp_self_test(int verbose) {
3294 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3295 mbedtls_ecp_group grp;
3296 mbedtls_ecp_point R, P;
3297 mbedtls_mpi m;
3299 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3300 /* Exponents especially adapted for secp192k1, which has the lowest
3301 * order n of all supported curves (secp192r1 is in a slightly larger
3302 * field but the order of its base point is slightly smaller). */
3303 const char *sw_exponents[] = {
3304 "000000000000000000000000000000000000000000000001", /* one */
3305 "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8C", /* n - 1 */
3306 "5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */
3307 "400000000000000000000000000000000000000000000000", /* one and zeros */
3308 "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */
3309 "555555555555555555555555555555555555555555555555", /* 101010... */
3311 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3312 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3313 const char *m_exponents[] = {
3314 /* Valid private values for Curve25519. In a build with Curve448
3315 * but not Curve25519, they will be adjusted in
3316 * self_test_adjust_exponent(). */
3317 "4000000000000000000000000000000000000000000000000000000000000000",
3318 "5C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C30",
3319 "5715ECCE24583F7A7023C24164390586842E816D7280A49EF6DF4EAE6B280BF8",
3320 "41A2B017516F6D254E1F002BCCBADD54BE30F8CEC737A0E912B4963B6BA74460",
3321 "5555555555555555555555555555555555555555555555555555555555555550",
3322 "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8",
3324 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3326 mbedtls_ecp_group_init(&grp);
3327 mbedtls_ecp_point_init(&R);
3328 mbedtls_ecp_point_init(&P);
3329 mbedtls_mpi_init(&m);
3331 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3332 /* Use secp192r1 if available, or any available curve */
3333 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
3334 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP192R1));
3335 #else
3336 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, mbedtls_ecp_curve_list()->grp_id));
3337 #endif
3339 if (verbose != 0)
3340 mbedtls_printf(" ECP SW test #1 (constant op_count, base point G): ");
3341 /* Do a dummy multiplication first to trigger precomputation */
3342 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&m, 2));
3343 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(&grp, &P, &m, &grp.G, NULL, NULL));
3344 ret = self_test_point(verbose,
3345 &grp, &R, &m, &grp.G,
3346 sw_exponents,
3347 sizeof(sw_exponents) / sizeof(sw_exponents[0]));
3348 if (ret != 0)
3349 goto cleanup;
3351 if (verbose != 0)
3352 mbedtls_printf(" ECP SW test #2 (constant op_count, other point): ");
3353 /* We computed P = 2G last time, use it */
3354 ret = self_test_point(verbose,
3355 &grp, &R, &m, &P,
3356 sw_exponents,
3357 sizeof(sw_exponents) / sizeof(sw_exponents[0]));
3358 if (ret != 0)
3359 goto cleanup;
3361 mbedtls_ecp_group_free(&grp);
3362 mbedtls_ecp_point_free(&R);
3363 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3365 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3366 if (verbose != 0)
3367 mbedtls_printf(" ECP Montgomery test (constant op_count): ");
3368 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
3369 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE25519));
3370 #elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
3371 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE448));
3372 #else
3373 #error "MBEDTLS_ECP_MONTGOMERY_ENABLED is defined, but no curve is supported for self-test"
3374 #endif
3375 ret = self_test_point(verbose,
3376 &grp, &R, &m, &grp.G,
3377 m_exponents,
3378 sizeof(m_exponents) / sizeof(m_exponents[0]));
3379 if (ret != 0)
3380 goto cleanup;
3381 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3383 cleanup:
3385 if (ret < 0 && verbose != 0)
3386 mbedtls_printf("Unexpected error, return code = %08X\n", (unsigned int) ret);
3388 mbedtls_ecp_group_free(&grp);
3389 mbedtls_ecp_point_free(&R);
3390 mbedtls_ecp_point_free(&P);
3391 mbedtls_mpi_free(&m);
3393 if (verbose != 0)
3394 mbedtls_printf("\n");
3396 return (ret);
3399 #endif /* MBEDTLS_SELF_TEST */
3401 #endif /* !MBEDTLS_ECP_ALT */
3403 #endif /* MBEDTLS_ECP_C */