1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com). */
109 #include <openssl/bn.h>
114 #include <openssl/err.h>
115 #include <openssl/mem.h>
116 #include <openssl/thread.h>
117 #include <openssl/type_check.h>
119 #include "internal.h"
120 #include "../../internal.h"
123 #if !defined(OPENSSL_NO_ASM) && \
124 (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \
125 defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64))
126 #define OPENSSL_BN_ASM_MONT
130 BN_MONT_CTX *BN_MONT_CTX_new(void) {
131 BN_MONT_CTX *ret = OPENSSL_malloc(sizeof(BN_MONT_CTX));
137 OPENSSL_memset(ret, 0, sizeof(BN_MONT_CTX));
144 void BN_MONT_CTX_free(BN_MONT_CTX *mont) {
154 BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, const BN_MONT_CTX *from) {
159 if (!BN_copy(&to->RR, &from->RR) ||
160 !BN_copy(&to->N, &from->N)) {
163 to->n0[0] = from->n0[0];
164 to->n0[1] = from->n0[1];
168 OPENSSL_COMPILE_ASSERT(BN_MONT_CTX_N0_LIMBS == 1 || BN_MONT_CTX_N0_LIMBS == 2,
169 BN_MONT_CTX_N0_LIMBS_VALUE_INVALID);
170 OPENSSL_COMPILE_ASSERT(sizeof(BN_ULONG) * BN_MONT_CTX_N0_LIMBS ==
171 sizeof(uint64_t), BN_MONT_CTX_set_64_bit_mismatch);
173 int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) {
174 if (BN_is_zero(mod)) {
175 OPENSSL_PUT_ERROR(BN, BN_R_DIV_BY_ZERO);
178 if (!BN_is_odd(mod)) {
179 OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
182 if (BN_is_negative(mod)) {
183 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
188 if (!BN_copy(&mont->N, mod)) {
189 OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
192 // |mont->N| is always stored minimally. Computing RR efficiently leaks the
193 // size of the modulus. While the modulus may be private in RSA (one of the
194 // primes), their sizes are public, so this is fine.
195 bn_set_minimal_width(&mont->N);
197 // Find n0 such that n0 * N == -1 (mod r).
199 // Only certain BN_BITS2<=32 platforms actually make use of n0[1]. For the
200 // others, we could use a shorter R value and use faster |BN_ULONG|-based
201 // math instead of |uint64_t|-based math, which would be double-precision.
202 // However, currently only the assembler files know which is which.
203 uint64_t n0 = bn_mont_n0(&mont->N);
204 mont->n0[0] = (BN_ULONG)n0;
205 #if BN_MONT_CTX_N0_LIMBS == 2
206 mont->n0[1] = (BN_ULONG)(n0 >> BN_BITS2);
211 BN_CTX *new_ctx = NULL;
213 new_ctx = BN_CTX_new();
214 if (new_ctx == NULL) {
220 // Save RR = R**2 (mod N). R is the smallest power of 2**BN_BITS2 such that R
221 // > mod. Even though the assembly on some 32-bit platforms works with 64-bit
222 // values, using |BN_BITS2| here, rather than |BN_MONT_CTX_N0_LIMBS *
223 // BN_BITS2|, is correct because R**2 will still be a multiple of the latter
224 // as |BN_MONT_CTX_N0_LIMBS| is either one or two.
225 unsigned lgBigR = mont->N.width * BN_BITS2;
226 int ok = bn_mod_exp_base_2_consttime(&mont->RR, lgBigR * 2, &mont->N, ctx);
227 BN_CTX_free(new_ctx);
231 BN_MONT_CTX *BN_MONT_CTX_new_for_modulus(const BIGNUM *mod, BN_CTX *ctx) {
232 BN_MONT_CTX *mont = BN_MONT_CTX_new();
234 !BN_MONT_CTX_set(mont, mod, ctx)) {
235 BN_MONT_CTX_free(mont);
241 int BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_MUTEX *lock,
242 const BIGNUM *mod, BN_CTX *bn_ctx) {
243 CRYPTO_MUTEX_lock_read(lock);
244 BN_MONT_CTX *ctx = *pmont;
245 CRYPTO_MUTEX_unlock_read(lock);
251 CRYPTO_MUTEX_lock_write(lock);
252 if (*pmont == NULL) {
253 *pmont = BN_MONT_CTX_new_for_modulus(mod, bn_ctx);
255 const int ok = *pmont != NULL;
256 CRYPTO_MUTEX_unlock_write(lock);
260 int BN_to_montgomery(BIGNUM *ret, const BIGNUM *a, const BN_MONT_CTX *mont,
262 return BN_mod_mul_montgomery(ret, a, &mont->RR, mont, ctx);
265 static int bn_from_montgomery_in_place(BN_ULONG *r, size_t num_r, BN_ULONG *a,
266 size_t num_a, const BN_MONT_CTX *mont) {
267 const BN_ULONG *n = mont->N.d;
268 size_t num_n = mont->N.width;
269 if (num_r != num_n || num_a != 2 * num_n) {
270 OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
274 // Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On
275 // input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r|
276 // includes |carry| which is stored separately.
277 BN_ULONG n0 = mont->n0[0];
279 for (size_t i = 0; i < num_n; i++) {
280 BN_ULONG v = bn_mul_add_words(a + i, n, num_n, a[i] * n0);
281 v += carry + a[i + num_n];
282 carry |= (v != a[i + num_n]);
283 carry &= (v <= a[i + num_n]);
287 // Shift |num_n| words to divide by R. We have |a| < 2 * |n|. Note that |a|
288 // includes |carry| which is stored separately.
291 // |a| thus requires at most one additional subtraction |n| to be reduced.
292 // Subtract |n| and select the answer in constant time.
293 OPENSSL_COMPILE_ASSERT(sizeof(BN_ULONG) <= sizeof(crypto_word_t),
294 crypto_word_t_too_small);
295 BN_ULONG v = bn_sub_words(r, a, n, num_n) - carry;
296 // |v| is one if |a| - |n| underflowed or zero if it did not. Note |v| cannot
297 // be -1. That would imply the subtraction did not fit in |num_n| words, and
298 // we know at most one subtraction is needed.
300 for (size_t i = 0; i < num_n; i++) {
301 r[i] = constant_time_select_w(v, a[i], r[i]);
307 static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r,
308 const BN_MONT_CTX *mont) {
310 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
314 const BIGNUM *n = &mont->N;
320 int max = 2 * n->width; // carry is stored separately
321 if (!bn_resize_words(r, max) ||
322 !bn_wexpand(ret, n->width)) {
326 ret->width = n->width;
328 return bn_from_montgomery_in_place(ret->d, ret->width, r->d, r->width, mont);
331 int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, const BN_MONT_CTX *mont,
343 ret = BN_from_montgomery_word(r, t, mont);
351 int bn_one_to_montgomery(BIGNUM *r, const BN_MONT_CTX *mont, BN_CTX *ctx) {
352 // If the high bit of |n| is set, R = 2^(width*BN_BITS2) < 2 * |n|, so we
353 // compute R - |n| rather than perform Montgomery reduction.
354 const BIGNUM *n = &mont->N;
355 if (n->width > 0 && (n->d[n->width - 1] >> (BN_BITS2 - 1)) != 0) {
356 if (!bn_wexpand(r, n->width)) {
359 r->d[0] = 0 - n->d[0];
360 for (int i = 1; i < n->width; i++) {
368 return BN_from_montgomery(r, &mont->RR, mont, ctx);
371 static int bn_mod_mul_montgomery_fallback(BIGNUM *r, const BIGNUM *a,
373 const BN_MONT_CTX *mont,
378 BIGNUM *tmp = BN_CTX_get(ctx);
384 if (!bn_sqr_consttime(tmp, a, ctx)) {
388 if (!bn_mul_consttime(tmp, a, b, ctx)) {
393 // reduce from aRR to aR
394 if (!BN_from_montgomery_word(r, tmp, mont)) {
405 int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
406 const BN_MONT_CTX *mont, BN_CTX *ctx) {
407 if (a->neg || b->neg) {
408 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
412 #if defined(OPENSSL_BN_ASM_MONT)
413 // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86.
414 int num = mont->N.width;
415 if (num >= (128 / BN_BITS2) &&
418 if (!bn_wexpand(r, num)) {
421 if (!bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) {
422 // The check above ensures this won't happen.
424 OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
433 return bn_mod_mul_montgomery_fallback(r, a, b, mont, ctx);
436 int bn_less_than_montgomery_R(const BIGNUM *bn, const BN_MONT_CTX *mont) {
437 return !BN_is_negative(bn) &&
438 bn_fits_in_words(bn, mont->N.width);
441 int bn_to_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
442 size_t num_a, const BN_MONT_CTX *mont) {
443 return bn_mod_mul_montgomery_small(r, num_r, a, num_a, mont->RR.d,
444 mont->RR.width, mont);
447 int bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
448 size_t num_a, const BN_MONT_CTX *mont) {
449 size_t num_n = mont->N.width;
450 if (num_a > 2 * num_n || num_r != num_n || num_n > BN_SMALL_MAX_WORDS) {
451 OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
454 BN_ULONG tmp[BN_SMALL_MAX_WORDS * 2];
455 size_t num_tmp = 2 * num_n;
456 OPENSSL_memcpy(tmp, a, num_a * sizeof(BN_ULONG));
457 OPENSSL_memset(tmp + num_a, 0, (num_tmp - num_a) * sizeof(BN_ULONG));
458 int ret = bn_from_montgomery_in_place(r, num_r, tmp, num_tmp, mont);
459 OPENSSL_cleanse(tmp, num_tmp * sizeof(BN_ULONG));
463 int bn_one_to_montgomery_small(BN_ULONG *r, size_t num_r,
464 const BN_MONT_CTX *mont) {
465 const BN_ULONG *n = mont->N.d;
466 size_t num_n = mont->N.width;
467 if (num_n == 0 || num_r != num_n) {
468 OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
472 // If the high bit of |n| is set, R = 2^(num_n*BN_BITS2) < 2 * |n|, so we
473 // compute R - |n| rather than perform Montgomery reduction.
474 if (num_n > 0 && (n[num_n - 1] >> (BN_BITS2 - 1)) != 0) {
476 for (size_t i = 1; i < num_n; i++) {
482 return bn_from_montgomery_small(r, num_r, mont->RR.d, mont->RR.width, mont);
485 int bn_mod_mul_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
486 size_t num_a, const BN_ULONG *b, size_t num_b,
487 const BN_MONT_CTX *mont) {
488 size_t num_n = mont->N.width;
489 if (num_r != num_n || num_a + num_b > 2 * num_n ||
490 num_n > BN_SMALL_MAX_WORDS) {
491 OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
495 #if defined(OPENSSL_BN_ASM_MONT)
496 // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86.
497 if (num_n >= (128 / BN_BITS2) &&
500 if (!bn_mul_mont(r, a, b, mont->N.d, mont->n0, num_n)) {
501 assert(0); // The check above ensures this won't happen.
502 OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
509 // Compute the product.
510 BN_ULONG tmp[2 * BN_SMALL_MAX_WORDS];
511 size_t num_tmp = 2 * num_n;
512 size_t num_ab = num_a + num_b;
513 if (a == b && num_a == num_b) {
514 if (!bn_sqr_small(tmp, num_ab, a, num_a)) {
517 } else if (!bn_mul_small(tmp, num_ab, a, num_a, b, num_b)) {
521 // Zero-extend to full width and reduce.
522 OPENSSL_memset(tmp + num_ab, 0, (num_tmp - num_ab) * sizeof(BN_ULONG));
523 int ret = bn_from_montgomery_in_place(r, num_r, tmp, num_tmp, mont);
524 OPENSSL_cleanse(tmp, num_tmp * sizeof(BN_ULONG));