2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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"
11 #include "internal/constant_time_locl.h"
18 # define alloca _alloca
20 #elif defined(__GNUC__)
22 # define alloca(s) __builtin_alloca((s))
31 #if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc))
32 # include "sparc_arch.h"
33 extern unsigned int OPENSSL_sparcv9cap_P[];
34 # define SPARC_T4_MONT
37 /* maximum precomputation table size for *variable* sliding windows */
40 /* this one works - simple but works */
41 int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
46 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
47 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
48 BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
53 if ((r == a) || (r == p))
58 if (rr == NULL || v == NULL)
61 if (BN_copy(v, a) == NULL)
63 bits = BN_num_bits(p);
66 if (BN_copy(rr, a) == NULL)
73 for (i = 1; i < bits; i++) {
74 if (!BN_sqr(v, v, ctx))
76 if (BN_is_bit_set(p, i)) {
77 if (!BN_mul(rr, rr, v, ctx))
81 if (r != rr && BN_copy(r, rr) == NULL)
91 int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
101 * For even modulus m = 2^k*m_odd, it might make sense to compute
102 * a^p mod m_odd and a^p mod 2^k separately (with Montgomery
103 * exponentiation for the odd part), using appropriate exponent
104 * reductions, and combine the results using the CRT.
106 * For now, we use Montgomery only if the modulus is odd; otherwise,
107 * exponentiation using the reciprocal-based quick remaindering
110 * (Timing obtained with expspeed.c [computations a^p mod m
111 * where a, p, m are of the same length: 256, 512, 1024, 2048,
112 * 4096, 8192 bits], compared to the running time of the
113 * standard algorithm:
115 * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration]
116 * 55 .. 77 % [UltraSparc processor, but
117 * debug-solaris-sparcv8-gcc conf.]
119 * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
120 * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
122 * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
123 * at 2048 and more bits, but at 512 and 1024 bits, it was
124 * slower even than the standard algorithm!
126 * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
127 * should be obtained when the new Montgomery reduction code
128 * has been integrated into OpenSSL.)
132 #define MONT_EXP_WORD
137 # ifdef MONT_EXP_WORD
138 if (a->top == 1 && !a->neg
139 && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)) {
140 BN_ULONG A = a->d[0];
141 ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
144 ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
149 ret = BN_mod_exp_recp(r, a, p, m, ctx);
153 ret = BN_mod_exp_simple(r, a, p, m, ctx);
161 int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
162 const BIGNUM *m, BN_CTX *ctx)
164 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
167 /* Table of variables obtained from 'ctx' */
168 BIGNUM *val[TABLE_SIZE];
171 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
172 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
173 BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
177 bits = BN_num_bits(p);
179 /* x**0 mod 1 is still zero. */
190 aa = BN_CTX_get(ctx);
191 val[0] = BN_CTX_get(ctx);
195 BN_RECP_CTX_init(&recp);
197 /* ignore sign of 'm' */
201 if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
204 if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
208 if (!BN_nnmod(val[0], a, m, ctx))
210 if (BN_is_zero(val[0])) {
216 window = BN_window_bits_for_exponent_size(bits);
218 if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
220 j = 1 << (window - 1);
221 for (i = 1; i < j; i++) {
222 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
223 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
228 start = 1; /* This is used to avoid multiplication etc
229 * when there is only the value '1' in the
231 wvalue = 0; /* The 'value' of the window */
232 wstart = bits - 1; /* The top bit of the window */
233 wend = 0; /* The bottom bit of the window */
239 if (BN_is_bit_set(p, wstart) == 0) {
241 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
249 * We now have wstart on a 'set' bit, we now need to work out how bit
250 * a window to do. To do this we need to scan forward until the last
251 * set bit before the end of the window
256 for (i = 1; i < window; i++) {
259 if (BN_is_bit_set(p, wstart - i)) {
260 wvalue <<= (i - wend);
266 /* wend is the size of the current window */
268 /* add the 'bytes above' */
270 for (i = 0; i < j; i++) {
271 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
275 /* wvalue will be an odd number < 2^window */
276 if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
279 /* move the 'window' down further */
289 BN_RECP_CTX_free(&recp);
294 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
295 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
297 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
301 /* Table of variables obtained from 'ctx' */
302 BIGNUM *val[TABLE_SIZE];
303 BN_MONT_CTX *mont = NULL;
305 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
306 return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
314 BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
317 bits = BN_num_bits(p);
319 /* x**0 mod 1 is still zero. */
332 val[0] = BN_CTX_get(ctx);
333 if (!d || !r || !val[0])
337 * If this is not done, things will break in the montgomery part
343 if ((mont = BN_MONT_CTX_new()) == NULL)
345 if (!BN_MONT_CTX_set(mont, m, ctx))
349 if (a->neg || BN_ucmp(a, m) >= 0) {
350 if (!BN_nnmod(val[0], a, m, ctx))
355 if (BN_is_zero(aa)) {
360 if (!BN_to_montgomery(val[0], aa, mont, ctx))
363 window = BN_window_bits_for_exponent_size(bits);
365 if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
367 j = 1 << (window - 1);
368 for (i = 1; i < j; i++) {
369 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
370 !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
375 start = 1; /* This is used to avoid multiplication etc
376 * when there is only the value '1' in the
378 wvalue = 0; /* The 'value' of the window */
379 wstart = bits - 1; /* The top bit of the window */
380 wend = 0; /* The bottom bit of the window */
382 #if 1 /* by Shay Gueron's suggestion */
383 j = m->top; /* borrow j */
384 if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
385 if (bn_wexpand(r, j) == NULL)
387 /* 2^(top*BN_BITS2) - m */
388 r->d[0] = (0 - m->d[0]) & BN_MASK2;
389 for (i = 1; i < j; i++)
390 r->d[i] = (~m->d[i]) & BN_MASK2;
393 * Upper words will be zero if the corresponding words of 'm' were
394 * 0xfff[...], so decrement r->top accordingly.
399 if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
402 if (BN_is_bit_set(p, wstart) == 0) {
404 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
413 * We now have wstart on a 'set' bit, we now need to work out how bit
414 * a window to do. To do this we need to scan forward until the last
415 * set bit before the end of the window
420 for (i = 1; i < window; i++) {
423 if (BN_is_bit_set(p, wstart - i)) {
424 wvalue <<= (i - wend);
430 /* wend is the size of the current window */
432 /* add the 'bytes above' */
434 for (i = 0; i < j; i++) {
435 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
439 /* wvalue will be an odd number < 2^window */
440 if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
443 /* move the 'window' down further */
450 #if defined(SPARC_T4_MONT)
451 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
452 j = mont->N.top; /* borrow j */
453 val[0]->d[0] = 1; /* borrow val[0] */
454 for (i = 1; i < j; i++)
457 if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
461 if (!BN_from_montgomery(rr, r, mont, ctx))
466 BN_MONT_CTX_free(mont);
472 #if defined(SPARC_T4_MONT)
473 static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
478 wordpos = bitpos / BN_BITS2;
480 if (wordpos >= 0 && wordpos < a->top) {
481 ret = a->d[wordpos] & BN_MASK2;
484 if (++wordpos < a->top)
485 ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
489 return ret & BN_MASK2;
494 * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
495 * layout so that accessing any of these table values shows the same access
496 * pattern as far as cache lines are concerned. The following functions are
497 * used to transfer a BIGNUM from/to that table.
500 static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
501 unsigned char *buf, int idx,
505 int width = 1 << window;
506 BN_ULONG *table = (BN_ULONG *)buf;
509 top = b->top; /* this works because 'buf' is explicitly
511 for (i = 0, j = idx; i < top; i++, j += width) {
518 static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
519 unsigned char *buf, int idx,
523 int width = 1 << window;
525 * We declare table 'volatile' in order to discourage compiler
526 * from reordering loads from the table. Concern is that if
527 * reordered in specific manner loads might give away the
528 * information we are trying to conceal. Some would argue that
529 * compiler can reorder them anyway, but it can as well be
530 * argued that doing so would be violation of standard...
532 volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
534 if (bn_wexpand(b, top) == NULL)
538 for (i = 0; i < top; i++, table += width) {
541 for (j = 0; j < width; j++) {
543 ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
549 int xstride = 1 << (window - 2);
550 BN_ULONG y0, y1, y2, y3;
552 i = idx >> (window - 2); /* equivalent of idx / xstride */
553 idx &= xstride - 1; /* equivalent of idx % xstride */
555 y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
556 y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
557 y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
558 y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
560 for (i = 0; i < top; i++, table += width) {
563 for (j = 0; j < xstride; j++) {
564 acc |= ( (table[j + 0 * xstride] & y0) |
565 (table[j + 1 * xstride] & y1) |
566 (table[j + 2 * xstride] & y2) |
567 (table[j + 3 * xstride] & y3) )
568 & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
581 * Given a pointer value, compute the next address that is a cache line
584 #define MOD_EXP_CTIME_ALIGN(x_) \
585 ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
588 * This variant of BN_mod_exp_mont() uses fixed windows and the special
589 * precomputation memory layout to limit data-dependency to a minimum to
590 * protect secret exponents (cf. the hyper-threading timing attacks pointed
591 * out by Colin Percival,
592 * http://www.daemonology.net/hyperthreading-considered-harmful/)
594 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
595 const BIGNUM *m, BN_CTX *ctx,
596 BN_MONT_CTX *in_mont)
598 int i, bits, ret = 0, window, wvalue;
600 BN_MONT_CTX *mont = NULL;
603 unsigned char *powerbufFree = NULL;
605 unsigned char *powerbuf = NULL;
607 #if defined(SPARC_T4_MONT)
616 BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
622 bits = BN_num_bits(p);
624 /* x**0 mod 1 is still zero. */
637 * Allocate a montgomery context if it was not supplied by the caller. If
638 * this is not done, things will break in the montgomery part.
643 if ((mont = BN_MONT_CTX_new()) == NULL)
645 if (!BN_MONT_CTX_set(mont, m, ctx))
651 * If the size of the operands allow it, perform the optimized
652 * RSAZ exponentiation. For further information see
653 * crypto/bn/rsaz_exp.c and accompanying assembly modules.
655 if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
656 && rsaz_avx2_eligible()) {
657 if (NULL == bn_wexpand(rr, 16))
659 RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
666 } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
667 if (NULL == bn_wexpand(rr, 8))
669 RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
678 /* Get the window size to use with size of p. */
679 window = BN_window_bits_for_ctime_exponent_size(bits);
680 #if defined(SPARC_T4_MONT)
681 if (window >= 5 && (top & 15) == 0 && top <= 64 &&
682 (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
683 (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
687 #if defined(OPENSSL_BN_ASM_MONT5)
689 window = 5; /* ~5% improvement for RSA2048 sign, and even
691 /* reserve space for mont->N.d[] copy */
692 powerbufLen += top * sizeof(mont->N.d[0]);
698 * Allocate a buffer large enough to hold all of the pre-computed powers
699 * of am, am itself and tmp.
701 numPowers = 1 << window;
702 powerbufLen += sizeof(m->d[0]) * (top * numPowers +
704 numPowers ? (2 * top) : numPowers));
706 if (powerbufLen < 3072)
708 alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
712 OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
716 powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
717 memset(powerbuf, 0, powerbufLen);
720 if (powerbufLen < 3072)
724 /* lay down tmp and am right after powers table */
725 tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
727 tmp.top = am.top = 0;
728 tmp.dmax = am.dmax = top;
729 tmp.neg = am.neg = 0;
730 tmp.flags = am.flags = BN_FLG_STATIC_DATA;
732 /* prepare a^0 in Montgomery domain */
733 #if 1 /* by Shay Gueron's suggestion */
734 if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
735 /* 2^(top*BN_BITS2) - m */
736 tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
737 for (i = 1; i < top; i++)
738 tmp.d[i] = (~m->d[i]) & BN_MASK2;
742 if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
745 /* prepare a^1 in Montgomery domain */
746 if (a->neg || BN_ucmp(a, m) >= 0) {
747 if (!BN_mod(&am, a, m, ctx))
749 if (!BN_to_montgomery(&am, &am, mont, ctx))
751 } else if (!BN_to_montgomery(&am, a, mont, ctx))
754 #if defined(SPARC_T4_MONT)
756 typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
757 const BN_ULONG *n0, const void *table,
758 int power, int bits);
759 int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
760 const BN_ULONG *n0, const void *table,
761 int power, int bits);
762 int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
763 const BN_ULONG *n0, const void *table,
764 int power, int bits);
765 int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
766 const BN_ULONG *n0, const void *table,
767 int power, int bits);
768 int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
769 const BN_ULONG *n0, const void *table,
770 int power, int bits);
771 static const bn_pwr5_mont_f pwr5_funcs[4] = {
772 bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
773 bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
775 bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
777 typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
778 const void *bp, const BN_ULONG *np,
780 int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
781 const BN_ULONG *np, const BN_ULONG *n0);
782 int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
783 const void *bp, const BN_ULONG *np,
785 int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
786 const void *bp, const BN_ULONG *np,
788 int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
789 const void *bp, const BN_ULONG *np,
791 static const bn_mul_mont_f mul_funcs[4] = {
792 bn_mul_mont_t4_8, bn_mul_mont_t4_16,
793 bn_mul_mont_t4_24, bn_mul_mont_t4_32
795 bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
797 void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
798 const void *bp, const BN_ULONG *np,
799 const BN_ULONG *n0, int num);
800 void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
801 const void *bp, const BN_ULONG *np,
802 const BN_ULONG *n0, int num);
803 void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
804 const void *table, const BN_ULONG *np,
805 const BN_ULONG *n0, int num, int power);
806 void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
807 void *table, size_t power);
808 void bn_gather5_t4(BN_ULONG *out, size_t num,
809 void *table, size_t power);
810 void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
812 BN_ULONG *np = mont->N.d, *n0 = mont->n0;
813 int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
817 * BN_to_montgomery can contaminate words above .top [in
818 * BN_DEBUG[_DEBUG] build]...
820 for (i = am.top; i < top; i++)
822 for (i = tmp.top; i < top; i++)
825 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
826 bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
827 if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
828 !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
829 bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
830 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
832 for (i = 3; i < 32; i++) {
833 /* Calculate a^i = a^(i-1) * a */
834 if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
835 !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
836 bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
837 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
840 /* switch to 64-bit domain */
841 np = alloca(top * sizeof(BN_ULONG));
843 bn_flip_t4(np, mont->N.d, top);
846 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
847 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
848 bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
851 * Scan the exponent one window at a time starting from the most
858 wvalue = bn_get_bits(p, bits + 1);
860 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
862 /* retry once and fall back */
863 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
867 wvalue >>= stride - 5;
869 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
870 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
871 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
872 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
873 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
874 bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
878 bn_flip_t4(tmp.d, tmp.d, top);
880 /* back to 32-bit domain */
882 bn_correct_top(&tmp);
883 OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
886 #if defined(OPENSSL_BN_ASM_MONT5)
887 if (window == 5 && top > 1) {
889 * This optimization uses ideas from http://eprint.iacr.org/2011/239,
890 * specifically optimization of cache-timing attack countermeasures
891 * and pre-computation optimization.
895 * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
896 * 512-bit RSA is hardly relevant, we omit it to spare size...
898 void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
899 const void *table, const BN_ULONG *np,
900 const BN_ULONG *n0, int num, int power);
901 void bn_scatter5(const BN_ULONG *inp, size_t num,
902 void *table, size_t power);
903 void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
904 void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
905 const void *table, const BN_ULONG *np,
906 const BN_ULONG *n0, int num, int power);
907 int bn_get_bits5(const BN_ULONG *ap, int off);
908 int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
909 const BN_ULONG *not_used, const BN_ULONG *np,
910 const BN_ULONG *n0, int num);
912 BN_ULONG *n0 = mont->n0, *np;
915 * BN_to_montgomery can contaminate words above .top [in
916 * BN_DEBUG[_DEBUG] build]...
918 for (i = am.top; i < top; i++)
920 for (i = tmp.top; i < top; i++)
924 * copy mont->N.d[] to improve cache locality
926 for (np = am.d + top, i = 0; i < top; i++)
927 np[i] = mont->N.d[i];
929 bn_scatter5(tmp.d, top, powerbuf, 0);
930 bn_scatter5(am.d, am.top, powerbuf, 1);
931 bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
932 bn_scatter5(tmp.d, top, powerbuf, 2);
935 for (i = 3; i < 32; i++) {
936 /* Calculate a^i = a^(i-1) * a */
937 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
938 bn_scatter5(tmp.d, top, powerbuf, i);
941 /* same as above, but uses squaring for 1/2 of operations */
942 for (i = 4; i < 32; i *= 2) {
943 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
944 bn_scatter5(tmp.d, top, powerbuf, i);
946 for (i = 3; i < 8; i += 2) {
948 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
949 bn_scatter5(tmp.d, top, powerbuf, i);
950 for (j = 2 * i; j < 32; j *= 2) {
951 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
952 bn_scatter5(tmp.d, top, powerbuf, j);
955 for (; i < 16; i += 2) {
956 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
957 bn_scatter5(tmp.d, top, powerbuf, i);
958 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
959 bn_scatter5(tmp.d, top, powerbuf, 2 * i);
961 for (; i < 32; i += 2) {
962 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
963 bn_scatter5(tmp.d, top, powerbuf, i);
967 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
968 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
969 bn_gather5(tmp.d, top, powerbuf, wvalue);
972 * Scan the exponent one window at a time starting from the most
977 for (wvalue = 0, i = 0; i < 5; i++, bits--)
978 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
980 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
981 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
982 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
983 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
984 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
985 bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
989 wvalue = bn_get_bits5(p->d, bits - 4);
991 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
995 ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
997 bn_correct_top(&tmp);
999 if (!BN_copy(rr, &tmp))
1001 goto err; /* non-zero ret means it's not error */
1006 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
1008 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
1012 * If the window size is greater than 1, then calculate
1013 * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
1014 * powers could instead be computed as (a^(i/2))^2 to use the slight
1015 * performance advantage of sqr over mul).
1018 if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
1020 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
1023 for (i = 3; i < numPowers; i++) {
1024 /* Calculate a^i = a^(i-1) * a */
1025 if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
1027 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
1034 for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
1035 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1036 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
1041 * Scan the exponent one window at a time starting from the most
1045 wvalue = 0; /* The 'value' of the window */
1047 /* Scan the window, squaring the result as we go */
1048 for (i = 0; i < window; i++, bits--) {
1049 if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
1051 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1055 * Fetch the appropriate pre-computed value from the pre-buf
1057 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
1061 /* Multiply the result into the intermediate result */
1062 if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
1067 /* Convert the final result from montgomery to standard format */
1068 #if defined(SPARC_T4_MONT)
1069 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
1070 am.d[0] = 1; /* borrow am */
1071 for (i = 1; i < top; i++)
1073 if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
1077 if (!BN_from_montgomery(rr, &tmp, mont, ctx))
1081 if (in_mont == NULL)
1082 BN_MONT_CTX_free(mont);
1083 if (powerbuf != NULL) {
1084 OPENSSL_cleanse(powerbuf, powerbufLen);
1085 OPENSSL_free(powerbufFree);
1091 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1092 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1094 BN_MONT_CTX *mont = NULL;
1095 int b, bits, ret = 0;
1100 #define BN_MOD_MUL_WORD(r, w, m) \
1101 (BN_mul_word(r, (w)) && \
1102 (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
1103 (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
1105 * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
1106 * probably more overhead than always using BN_mod (which uses BN_copy if
1107 * a similar test returns true).
1110 * We can use BN_mod and do not need BN_nnmod because our accumulator is
1111 * never negative (the result of BN_mod does not depend on the sign of
1114 #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
1115 (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
1117 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
1118 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1119 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1126 if (!BN_is_odd(m)) {
1127 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
1131 a %= m->d[0]; /* make sure that 'a' is reduced */
1133 bits = BN_num_bits(p);
1135 /* x**0 mod 1 is still zero. */
1151 d = BN_CTX_get(ctx);
1152 r = BN_CTX_get(ctx);
1153 t = BN_CTX_get(ctx);
1154 if (d == NULL || r == NULL || t == NULL)
1157 if (in_mont != NULL)
1160 if ((mont = BN_MONT_CTX_new()) == NULL)
1162 if (!BN_MONT_CTX_set(mont, m, ctx))
1166 r_is_one = 1; /* except for Montgomery factor */
1170 /* The result is accumulated in the product r*w. */
1171 w = a; /* bit 'bits-1' of 'p' is always set */
1172 for (b = bits - 2; b >= 0; b--) {
1173 /* First, square r*w. */
1175 if ((next_w / w) != w) { /* overflow */
1177 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1181 if (!BN_MOD_MUL_WORD(r, w, m))
1188 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
1192 /* Second, multiply r*w by 'a' if exponent bit is set. */
1193 if (BN_is_bit_set(p, b)) {
1195 if ((next_w / a) != w) { /* overflow */
1197 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1201 if (!BN_MOD_MUL_WORD(r, w, m))
1210 /* Finally, set r:=r*w. */
1213 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1217 if (!BN_MOD_MUL_WORD(r, w, m))
1222 if (r_is_one) { /* can happen only if a == 1 */
1226 if (!BN_from_montgomery(rr, r, mont, ctx))
1231 if (in_mont == NULL)
1232 BN_MONT_CTX_free(mont);
1238 /* The old fallback, simple version :-) */
1239 int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1240 const BIGNUM *m, BN_CTX *ctx)
1242 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
1245 /* Table of variables obtained from 'ctx' */
1246 BIGNUM *val[TABLE_SIZE];
1248 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
1249 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1250 BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1254 bits = BN_num_bits(p);
1256 /* x**0 mod 1 is still zero. */
1267 d = BN_CTX_get(ctx);
1268 val[0] = BN_CTX_get(ctx);
1272 if (!BN_nnmod(val[0], a, m, ctx))
1274 if (BN_is_zero(val[0])) {
1280 window = BN_window_bits_for_exponent_size(bits);
1282 if (!BN_mod_mul(d, val[0], val[0], m, ctx))
1284 j = 1 << (window - 1);
1285 for (i = 1; i < j; i++) {
1286 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
1287 !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
1292 start = 1; /* This is used to avoid multiplication etc
1293 * when there is only the value '1' in the
1295 wvalue = 0; /* The 'value' of the window */
1296 wstart = bits - 1; /* The top bit of the window */
1297 wend = 0; /* The bottom bit of the window */
1303 if (BN_is_bit_set(p, wstart) == 0) {
1305 if (!BN_mod_mul(r, r, r, m, ctx))
1313 * We now have wstart on a 'set' bit, we now need to work out how bit
1314 * a window to do. To do this we need to scan forward until the last
1315 * set bit before the end of the window
1320 for (i = 1; i < window; i++) {
1323 if (BN_is_bit_set(p, wstart - i)) {
1324 wvalue <<= (i - wend);
1330 /* wend is the size of the current window */
1332 /* add the 'bytes above' */
1334 for (i = 0; i < j; i++) {
1335 if (!BN_mod_mul(r, r, r, m, ctx))
1339 /* wvalue will be an odd number < 2^window */
1340 if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
1343 /* move the 'window' down further */