2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "internal/cryptlib.h"
14 * bn_mod_inverse_no_branch is a special version of BN_mod_inverse. It does
15 * not contain branches that may leak sensitive information.
17 * This is a static function, we ensure all callers in this file pass valid
18 * arguments: all passed pointers here are non-NULL.
21 BIGNUM *bn_mod_inverse_no_branch(BIGNUM *in,
22 const BIGNUM *a, const BIGNUM *n,
23 BN_CTX *ctx, int *pnoinv)
25 BIGNUM *A, *B, *X, *Y, *M, *D, *T, *R = NULL;
53 if (BN_copy(B, a) == NULL)
55 if (BN_copy(A, n) == NULL)
59 if (B->neg || (BN_ucmp(B, A) >= 0)) {
61 * Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked,
62 * BN_div_no_branch will be called eventually.
67 BN_with_flags(&local_B, B, BN_FLG_CONSTTIME);
68 if (!BN_nnmod(B, &local_B, A, ctx))
70 /* Ensure local_B goes out of scope before any further use of B */
75 * From B = a mod |n|, A = |n| it follows that
78 * -sign*X*a == B (mod |n|),
79 * sign*Y*a == A (mod |n|).
82 while (!BN_is_zero(B)) {
87 * (*) -sign*X*a == B (mod |n|),
88 * sign*Y*a == A (mod |n|)
92 * Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked,
93 * BN_div_no_branch will be called eventually.
98 BN_with_flags(&local_A, A, BN_FLG_CONSTTIME);
100 /* (D, M) := (A/B, A%B) ... */
101 if (!BN_div(D, M, &local_A, B, ctx))
103 /* Ensure local_A goes out of scope before any further use of A */
110 * (**) sign*Y*a == D*B + M (mod |n|).
113 tmp = A; /* keep the BIGNUM object, the value does not
116 /* (A, B) := (B, A mod B) ... */
119 /* ... so we have 0 <= B < A again */
122 * Since the former M is now B and the former B is now A,
123 * (**) translates into
124 * sign*Y*a == D*A + B (mod |n|),
126 * sign*Y*a - D*A == B (mod |n|).
127 * Similarly, (*) translates into
128 * -sign*X*a == A (mod |n|).
131 * sign*Y*a + D*sign*X*a == B (mod |n|),
133 * sign*(Y + D*X)*a == B (mod |n|).
135 * So if we set (X, Y, sign) := (Y + D*X, X, -sign), we arrive back at
136 * -sign*X*a == B (mod |n|),
137 * sign*Y*a == A (mod |n|).
138 * Note that X and Y stay non-negative all the time.
141 if (!BN_mul(tmp, D, X, ctx))
143 if (!BN_add(tmp, tmp, Y))
146 M = Y; /* keep the BIGNUM object, the value does not
154 * The while loop (Euclid's algorithm) ends when
157 * sign*Y*a == A (mod |n|),
158 * where Y is non-negative.
162 if (!BN_sub(Y, n, Y))
165 /* Now Y*a == A (mod |n|). */
168 /* Y*a == 1 (mod |n|) */
169 if (!Y->neg && BN_ucmp(Y, n) < 0) {
173 if (!BN_nnmod(R, Y, n, ctx))
178 /* caller sets the BN_R_NO_INVERSE error */
186 if ((ret == NULL) && (in == NULL))
194 * This is an internal function, we assume all callers pass valid arguments:
195 * all pointers passed here are assumed non-NULL.
197 BIGNUM *int_bn_mod_inverse(BIGNUM *in,
198 const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx,
201 BIGNUM *A, *B, *X, *Y, *M, *D, *T, *R = NULL;
205 /* This is invalid input so we don't worry about constant time here */
206 if (BN_abs_is_word(n, 1) || BN_is_zero(n)) {
213 if ((BN_get_flags(a, BN_FLG_CONSTTIME) != 0)
214 || (BN_get_flags(n, BN_FLG_CONSTTIME) != 0)) {
215 return bn_mod_inverse_no_branch(in, a, n, ctx, pnoinv);
242 if (BN_copy(B, a) == NULL)
244 if (BN_copy(A, n) == NULL)
247 if (B->neg || (BN_ucmp(B, A) >= 0)) {
248 if (!BN_nnmod(B, B, A, ctx))
253 * From B = a mod |n|, A = |n| it follows that
256 * -sign*X*a == B (mod |n|),
257 * sign*Y*a == A (mod |n|).
260 if (BN_is_odd(n) && (BN_num_bits(n) <= 2048)) {
262 * Binary inversion algorithm; requires odd modulus. This is faster
263 * than the general algorithm if the modulus is sufficiently small
264 * (about 400 .. 500 bits on 32-bit systems, but much more on 64-bit
269 while (!BN_is_zero(B)) {
273 * (1) -sign*X*a == B (mod |n|),
274 * (2) sign*Y*a == A (mod |n|)
278 * Now divide B by the maximum possible power of two in the
279 * integers, and divide X by the same value mod |n|. When we're
280 * done, (1) still holds.
283 while (!BN_is_bit_set(B, shift)) { /* note that 0 < B */
287 if (!BN_uadd(X, X, n))
291 * now X is even, so we can easily divide it by two
293 if (!BN_rshift1(X, X))
297 if (!BN_rshift(B, B, shift))
302 * Same for A and Y. Afterwards, (2) still holds.
305 while (!BN_is_bit_set(A, shift)) { /* note that 0 < A */
309 if (!BN_uadd(Y, Y, n))
313 if (!BN_rshift1(Y, Y))
317 if (!BN_rshift(A, A, shift))
322 * We still have (1) and (2).
323 * Both A and B are odd.
324 * The following computations ensure that
328 * (1) -sign*X*a == B (mod |n|),
329 * (2) sign*Y*a == A (mod |n|),
331 * and that either A or B is even in the next iteration.
333 if (BN_ucmp(B, A) >= 0) {
334 /* -sign*(X + Y)*a == B - A (mod |n|) */
335 if (!BN_uadd(X, X, Y))
338 * NB: we could use BN_mod_add_quick(X, X, Y, n), but that
339 * actually makes the algorithm slower
341 if (!BN_usub(B, B, A))
344 /* sign*(X + Y)*a == A - B (mod |n|) */
345 if (!BN_uadd(Y, Y, X))
348 * as above, BN_mod_add_quick(Y, Y, X, n) would slow things down
350 if (!BN_usub(A, A, B))
355 /* general inversion algorithm */
357 while (!BN_is_zero(B)) {
362 * (*) -sign*X*a == B (mod |n|),
363 * sign*Y*a == A (mod |n|)
366 /* (D, M) := (A/B, A%B) ... */
367 if (BN_num_bits(A) == BN_num_bits(B)) {
370 if (!BN_sub(M, A, B))
372 } else if (BN_num_bits(A) == BN_num_bits(B) + 1) {
373 /* A/B is 1, 2, or 3 */
374 if (!BN_lshift1(T, B))
376 if (BN_ucmp(A, T) < 0) {
377 /* A < 2*B, so D=1 */
380 if (!BN_sub(M, A, B))
383 /* A >= 2*B, so D=2 or D=3 */
384 if (!BN_sub(M, A, T))
386 if (!BN_add(D, T, B))
387 goto err; /* use D (:= 3*B) as temp */
388 if (BN_ucmp(A, D) < 0) {
389 /* A < 3*B, so D=2 */
390 if (!BN_set_word(D, 2))
393 * M (= A - 2*B) already has the correct value
396 /* only D=3 remains */
397 if (!BN_set_word(D, 3))
400 * currently M = A - 2*B, but we need M = A - 3*B
402 if (!BN_sub(M, M, B))
407 if (!BN_div(D, M, A, B, ctx))
415 * (**) sign*Y*a == D*B + M (mod |n|).
418 tmp = A; /* keep the BIGNUM object, the value does not matter */
420 /* (A, B) := (B, A mod B) ... */
423 /* ... so we have 0 <= B < A again */
426 * Since the former M is now B and the former B is now A,
427 * (**) translates into
428 * sign*Y*a == D*A + B (mod |n|),
430 * sign*Y*a - D*A == B (mod |n|).
431 * Similarly, (*) translates into
432 * -sign*X*a == A (mod |n|).
435 * sign*Y*a + D*sign*X*a == B (mod |n|),
437 * sign*(Y + D*X)*a == B (mod |n|).
439 * So if we set (X, Y, sign) := (Y + D*X, X, -sign), we arrive back at
440 * -sign*X*a == B (mod |n|),
441 * sign*Y*a == A (mod |n|).
442 * Note that X and Y stay non-negative all the time.
446 * most of the time D is very small, so we can optimize tmp := D*X+Y
449 if (!BN_add(tmp, X, Y))
452 if (BN_is_word(D, 2)) {
453 if (!BN_lshift1(tmp, X))
455 } else if (BN_is_word(D, 4)) {
456 if (!BN_lshift(tmp, X, 2))
458 } else if (D->top == 1) {
459 if (!BN_copy(tmp, X))
461 if (!BN_mul_word(tmp, D->d[0]))
464 if (!BN_mul(tmp, D, X, ctx))
467 if (!BN_add(tmp, tmp, Y))
471 M = Y; /* keep the BIGNUM object, the value does not matter */
479 * The while loop (Euclid's algorithm) ends when
482 * sign*Y*a == A (mod |n|),
483 * where Y is non-negative.
487 if (!BN_sub(Y, n, Y))
490 /* Now Y*a == A (mod |n|). */
493 /* Y*a == 1 (mod |n|) */
494 if (!Y->neg && BN_ucmp(Y, n) < 0) {
498 if (!BN_nnmod(R, Y, n, ctx))
507 if ((ret == NULL) && (in == NULL))
514 /* solves ax == 1 (mod n) */
515 BIGNUM *BN_mod_inverse(BIGNUM *in,
516 const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx)
518 BN_CTX *new_ctx = NULL;
523 ctx = new_ctx = BN_CTX_new_ex(NULL);
525 ERR_raise(ERR_LIB_BN, ERR_R_BN_LIB);
530 rv = int_bn_mod_inverse(in, a, n, ctx, &noinv);
532 ERR_raise(ERR_LIB_BN, BN_R_NO_INVERSE);
533 BN_CTX_free(new_ctx);
538 * The numbers a and b are coprime if the only positive integer that is a
539 * divisor of both of them is 1.
542 * Coprimes have the property: b has a multiplicative inverse modulo a
543 * i.e there is some value x such that bx = 1 (mod a).
545 * Testing the modulo inverse is currently much faster than the constant
546 * time version of BN_gcd().
548 int BN_are_coprime(BIGNUM *a, const BIGNUM *b, BN_CTX *ctx)
554 tmp = BN_CTX_get(ctx);
559 BN_set_flags(a, BN_FLG_CONSTTIME);
560 ret = (BN_mod_inverse(tmp, a, b, ctx) != NULL);
561 /* Clear any errors (an error is returned if there is no inverse) */
569 * This function is based on the constant-time GCD work by Bernstein and Yang:
570 * https://eprint.iacr.org/2019/266
571 * Generalized fast GCD function to allow even inputs.
572 * The algorithm first finds the shared powers of 2 between
573 * the inputs, and removes them, reducing at least one of the
574 * inputs to an odd value. Then it proceeds to calculate the GCD.
575 * Before returning the resulting GCD, we take care of adding
576 * back the powers of two removed at the beginning.
577 * Note 1: we assume the bit length of both inputs is public information,
578 * since access to top potentially leaks this information.
580 int BN_gcd(BIGNUM *r, const BIGNUM *in_a, const BIGNUM *in_b, BN_CTX *ctx)
582 BIGNUM *g, *temp = NULL;
584 int i, j, top, rlen, glen, m, bit = 1, delta = 1, cond = 0, shifts = 0, ret = 0;
586 /* Note 2: zero input corner cases are not constant-time since they are
587 * handled immediately. An attacker can run an attack under this
588 * assumption without the need of side-channel information. */
589 if (BN_is_zero(in_b)) {
590 ret = BN_copy(r, in_a) != NULL;
594 if (BN_is_zero(in_a)) {
595 ret = BN_copy(r, in_b) != NULL;
604 temp = BN_CTX_get(ctx);
607 /* make r != 0, g != 0 even, so BN_rshift is not a potential nop */
609 || !BN_lshift1(g, in_b)
610 || !BN_lshift1(r, in_a))
613 /* find shared powers of two, i.e. "shifts" >= 1 */
614 for (i = 0; i < r->dmax && i < g->dmax; i++) {
615 mask = ~(r->d[i] | g->d[i]);
616 for (j = 0; j < BN_BITS2; j++) {
623 /* subtract shared powers of two; shifts >= 1 */
624 if (!BN_rshift(r, r, shifts)
625 || !BN_rshift(g, g, shifts))
628 /* expand to biggest nword, with room for a possible extra word */
629 top = 1 + ((r->top >= g->top) ? r->top : g->top);
630 if (bn_wexpand(r, top) == NULL
631 || bn_wexpand(g, top) == NULL
632 || bn_wexpand(temp, top) == NULL)
635 /* re arrange inputs s.t. r is odd */
636 BN_consttime_swap((~r->d[0]) & 1, r, g, top);
638 /* compute the number of iterations */
639 rlen = BN_num_bits(r);
640 glen = BN_num_bits(g);
641 m = 4 + 3 * ((rlen >= glen) ? rlen : glen);
643 for (i = 0; i < m; i++) {
644 /* conditionally flip signs if delta is positive and g is odd */
645 cond = (-delta >> (8 * sizeof(delta) - 1)) & g->d[0] & 1
646 /* make sure g->top > 0 (i.e. if top == 0 then g == 0 always) */
647 & (~((g->top - 1) >> (sizeof(g->top) * 8 - 1)));
648 delta = (-cond & -delta) | ((cond - 1) & delta);
651 BN_consttime_swap(cond, r, g, top);
653 /* elimination step */
655 if (!BN_add(temp, g, r))
657 BN_consttime_swap(g->d[0] & 1 /* g is odd */
658 /* make sure g->top > 0 (i.e. if top == 0 then g == 0 always) */
659 & (~((g->top - 1) >> (sizeof(g->top) * 8 - 1))),
661 if (!BN_rshift1(g, g))
665 /* remove possible negative sign */
667 /* add powers of 2 removed, then correct the artificial shift */
668 if (!BN_lshift(r, r, shifts)
669 || !BN_rshift1(r, r))