2 * Copyright 1995-2017 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_get_flags(a, BN_FLG_CONSTTIME) != 0) {
48 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
49 BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
54 rr = ((r == a) || (r == p)) ? BN_CTX_get(ctx) : r;
56 if (rr == NULL || v == NULL)
59 if (BN_copy(v, a) == NULL)
61 bits = BN_num_bits(p);
64 if (BN_copy(rr, a) == NULL)
71 for (i = 1; i < bits; i++) {
72 if (!BN_sqr(v, v, ctx))
74 if (BN_is_bit_set(p, i)) {
75 if (!BN_mul(rr, rr, v, ctx))
79 if (r != rr && BN_copy(r, rr) == NULL)
89 int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
99 * For even modulus m = 2^k*m_odd, it might make sense to compute
100 * a^p mod m_odd and a^p mod 2^k separately (with Montgomery
101 * exponentiation for the odd part), using appropriate exponent
102 * reductions, and combine the results using the CRT.
104 * For now, we use Montgomery only if the modulus is odd; otherwise,
105 * exponentiation using the reciprocal-based quick remaindering
108 * (Timing obtained with expspeed.c [computations a^p mod m
109 * where a, p, m are of the same length: 256, 512, 1024, 2048,
110 * 4096, 8192 bits], compared to the running time of the
111 * standard algorithm:
113 * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration]
114 * 55 .. 77 % [UltraSparc processor, but
115 * debug-solaris-sparcv8-gcc conf.]
117 * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
118 * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
120 * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
121 * at 2048 and more bits, but at 512 and 1024 bits, it was
122 * slower even than the standard algorithm!
124 * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
125 * should be obtained when the new Montgomery reduction code
126 * has been integrated into OpenSSL.)
130 #define MONT_EXP_WORD
135 # ifdef MONT_EXP_WORD
136 if (a->top == 1 && !a->neg
137 && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)
138 && (BN_get_flags(a, BN_FLG_CONSTTIME) == 0)
139 && (BN_get_flags(m, 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_get_flags(a, BN_FLG_CONSTTIME) != 0
173 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
174 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
175 BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
179 bits = BN_num_bits(p);
181 /* x**0 mod 1 is still zero. */
192 aa = BN_CTX_get(ctx);
193 val[0] = BN_CTX_get(ctx);
197 BN_RECP_CTX_init(&recp);
199 /* ignore sign of 'm' */
203 if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
206 if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
210 if (!BN_nnmod(val[0], a, m, ctx))
212 if (BN_is_zero(val[0])) {
218 window = BN_window_bits_for_exponent_size(bits);
220 if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
222 j = 1 << (window - 1);
223 for (i = 1; i < j; i++) {
224 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
225 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
230 start = 1; /* This is used to avoid multiplication etc
231 * when there is only the value '1' in the
233 wvalue = 0; /* The 'value' of the window */
234 wstart = bits - 1; /* The top bit of the window */
235 wend = 0; /* The bottom bit of the window */
241 if (BN_is_bit_set(p, wstart) == 0) {
243 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
251 * We now have wstart on a 'set' bit, we now need to work out how bit
252 * a window to do. To do this we need to scan forward until the last
253 * set bit before the end of the window
258 for (i = 1; i < window; i++) {
261 if (BN_is_bit_set(p, wstart - i)) {
262 wvalue <<= (i - wend);
268 /* wend is the size of the current window */
270 /* add the 'bytes above' */
272 for (i = 0; i < j; i++) {
273 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
277 /* wvalue will be an odd number < 2^window */
278 if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
281 /* move the 'window' down further */
291 BN_RECP_CTX_free(&recp);
296 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
297 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
299 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
303 /* Table of variables obtained from 'ctx' */
304 BIGNUM *val[TABLE_SIZE];
305 BN_MONT_CTX *mont = NULL;
307 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
308 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
309 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
310 return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
318 BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
321 bits = BN_num_bits(p);
323 /* x**0 mod 1 is still zero. */
336 val[0] = BN_CTX_get(ctx);
341 * If this is not done, things will break in the montgomery part
347 if ((mont = BN_MONT_CTX_new()) == NULL)
349 if (!BN_MONT_CTX_set(mont, m, ctx))
353 if (a->neg || BN_ucmp(a, m) >= 0) {
354 if (!BN_nnmod(val[0], a, m, ctx))
359 if (BN_is_zero(aa)) {
364 if (!BN_to_montgomery(val[0], aa, mont, ctx))
367 window = BN_window_bits_for_exponent_size(bits);
369 if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
371 j = 1 << (window - 1);
372 for (i = 1; i < j; i++) {
373 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
374 !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
379 start = 1; /* This is used to avoid multiplication etc
380 * when there is only the value '1' in the
382 wvalue = 0; /* The 'value' of the window */
383 wstart = bits - 1; /* The top bit of the window */
384 wend = 0; /* The bottom bit of the window */
386 #if 1 /* by Shay Gueron's suggestion */
387 j = m->top; /* borrow j */
388 if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
389 if (bn_wexpand(r, j) == NULL)
391 /* 2^(top*BN_BITS2) - m */
392 r->d[0] = (0 - m->d[0]) & BN_MASK2;
393 for (i = 1; i < j; i++)
394 r->d[i] = (~m->d[i]) & BN_MASK2;
397 * Upper words will be zero if the corresponding words of 'm' were
398 * 0xfff[...], so decrement r->top accordingly.
403 if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
406 if (BN_is_bit_set(p, wstart) == 0) {
408 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
417 * We now have wstart on a 'set' bit, we now need to work out how bit
418 * a window to do. To do this we need to scan forward until the last
419 * set bit before the end of the window
424 for (i = 1; i < window; i++) {
427 if (BN_is_bit_set(p, wstart - i)) {
428 wvalue <<= (i - wend);
434 /* wend is the size of the current window */
436 /* add the 'bytes above' */
438 for (i = 0; i < j; i++) {
439 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
443 /* wvalue will be an odd number < 2^window */
444 if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
447 /* move the 'window' down further */
454 #if defined(SPARC_T4_MONT)
455 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
456 j = mont->N.top; /* borrow j */
457 val[0]->d[0] = 1; /* borrow val[0] */
458 for (i = 1; i < j; i++)
461 if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
465 if (!BN_from_montgomery(rr, r, mont, ctx))
470 BN_MONT_CTX_free(mont);
476 #if defined(SPARC_T4_MONT)
477 static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
482 wordpos = bitpos / BN_BITS2;
484 if (wordpos >= 0 && wordpos < a->top) {
485 ret = a->d[wordpos] & BN_MASK2;
488 if (++wordpos < a->top)
489 ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
493 return ret & BN_MASK2;
498 * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
499 * layout so that accessing any of these table values shows the same access
500 * pattern as far as cache lines are concerned. The following functions are
501 * used to transfer a BIGNUM from/to that table.
504 static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
505 unsigned char *buf, int idx,
509 int width = 1 << window;
510 BN_ULONG *table = (BN_ULONG *)buf;
513 top = b->top; /* this works because 'buf' is explicitly
515 for (i = 0, j = idx; i < top; i++, j += width) {
522 static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
523 unsigned char *buf, int idx,
527 int width = 1 << window;
529 * We declare table 'volatile' in order to discourage compiler
530 * from reordering loads from the table. Concern is that if
531 * reordered in specific manner loads might give away the
532 * information we are trying to conceal. Some would argue that
533 * compiler can reorder them anyway, but it can as well be
534 * argued that doing so would be violation of standard...
536 volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
538 if (bn_wexpand(b, top) == NULL)
542 for (i = 0; i < top; i++, table += width) {
545 for (j = 0; j < width; j++) {
547 ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
553 int xstride = 1 << (window - 2);
554 BN_ULONG y0, y1, y2, y3;
556 i = idx >> (window - 2); /* equivalent of idx / xstride */
557 idx &= xstride - 1; /* equivalent of idx % xstride */
559 y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
560 y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
561 y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
562 y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
564 for (i = 0; i < top; i++, table += width) {
567 for (j = 0; j < xstride; j++) {
568 acc |= ( (table[j + 0 * xstride] & y0) |
569 (table[j + 1 * xstride] & y1) |
570 (table[j + 2 * xstride] & y2) |
571 (table[j + 3 * xstride] & y3) )
572 & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
585 * Given a pointer value, compute the next address that is a cache line
588 #define MOD_EXP_CTIME_ALIGN(x_) \
589 ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
592 * This variant of BN_mod_exp_mont() uses fixed windows and the special
593 * precomputation memory layout to limit data-dependency to a minimum to
594 * protect secret exponents (cf. the hyper-threading timing attacks pointed
595 * out by Colin Percival,
596 * http://www.daemonology.net/hyperthreading-considered-harmful/)
598 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
599 const BIGNUM *m, BN_CTX *ctx,
600 BN_MONT_CTX *in_mont)
602 int i, bits, ret = 0, window, wvalue;
604 BN_MONT_CTX *mont = NULL;
607 unsigned char *powerbufFree = NULL;
609 unsigned char *powerbuf = NULL;
611 #if defined(SPARC_T4_MONT)
620 BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
626 bits = BN_num_bits(p);
628 /* x**0 mod 1 is still zero. */
641 * Allocate a montgomery context if it was not supplied by the caller. If
642 * this is not done, things will break in the montgomery part.
647 if ((mont = BN_MONT_CTX_new()) == NULL)
649 if (!BN_MONT_CTX_set(mont, m, ctx))
656 * If the size of the operands allow it, perform the optimized
657 * RSAZ exponentiation. For further information see
658 * crypto/bn/rsaz_exp.c and accompanying assembly modules.
660 if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
661 && rsaz_avx2_eligible()) {
662 if (NULL == bn_wexpand(rr, 16))
664 RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
671 } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
672 if (NULL == bn_wexpand(rr, 8))
674 RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
684 /* Get the window size to use with size of p. */
685 window = BN_window_bits_for_ctime_exponent_size(bits);
686 #if defined(SPARC_T4_MONT)
687 if (window >= 5 && (top & 15) == 0 && top <= 64 &&
688 (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
689 (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
693 #if defined(OPENSSL_BN_ASM_MONT5)
695 window = 5; /* ~5% improvement for RSA2048 sign, and even
697 /* reserve space for mont->N.d[] copy */
698 powerbufLen += top * sizeof(mont->N.d[0]);
704 * Allocate a buffer large enough to hold all of the pre-computed powers
705 * of am, am itself and tmp.
707 numPowers = 1 << window;
708 powerbufLen += sizeof(m->d[0]) * (top * numPowers +
710 numPowers ? (2 * top) : numPowers));
712 if (powerbufLen < 3072)
714 alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
718 OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
722 powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
723 memset(powerbuf, 0, powerbufLen);
726 if (powerbufLen < 3072)
730 /* lay down tmp and am right after powers table */
731 tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
733 tmp.top = am.top = 0;
734 tmp.dmax = am.dmax = top;
735 tmp.neg = am.neg = 0;
736 tmp.flags = am.flags = BN_FLG_STATIC_DATA;
738 /* prepare a^0 in Montgomery domain */
739 #if 1 /* by Shay Gueron's suggestion */
740 if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
741 /* 2^(top*BN_BITS2) - m */
742 tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
743 for (i = 1; i < top; i++)
744 tmp.d[i] = (~m->d[i]) & BN_MASK2;
748 if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
751 /* prepare a^1 in Montgomery domain */
752 if (a->neg || BN_ucmp(a, m) >= 0) {
753 if (!BN_nnmod(&am, a, m, ctx))
755 if (!BN_to_montgomery(&am, &am, mont, ctx))
757 } else if (!BN_to_montgomery(&am, a, mont, ctx))
760 #if defined(SPARC_T4_MONT)
762 typedef int (*bn_pwr5_mont_f) (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_8(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_16(BN_ULONG *tp, const BN_ULONG *np,
769 const BN_ULONG *n0, const void *table,
770 int power, int bits);
771 int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
772 const BN_ULONG *n0, const void *table,
773 int power, int bits);
774 int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
775 const BN_ULONG *n0, const void *table,
776 int power, int bits);
777 static const bn_pwr5_mont_f pwr5_funcs[4] = {
778 bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
779 bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
781 bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
783 typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
784 const void *bp, const BN_ULONG *np,
786 int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
787 const BN_ULONG *np, const BN_ULONG *n0);
788 int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
789 const void *bp, const BN_ULONG *np,
791 int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
792 const void *bp, const BN_ULONG *np,
794 int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
795 const void *bp, const BN_ULONG *np,
797 static const bn_mul_mont_f mul_funcs[4] = {
798 bn_mul_mont_t4_8, bn_mul_mont_t4_16,
799 bn_mul_mont_t4_24, bn_mul_mont_t4_32
801 bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
803 void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
804 const void *bp, const BN_ULONG *np,
805 const BN_ULONG *n0, int num);
806 void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
807 const void *bp, const BN_ULONG *np,
808 const BN_ULONG *n0, int num);
809 void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
810 const void *table, const BN_ULONG *np,
811 const BN_ULONG *n0, int num, int power);
812 void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
813 void *table, size_t power);
814 void bn_gather5_t4(BN_ULONG *out, size_t num,
815 void *table, size_t power);
816 void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
818 BN_ULONG *np = mont->N.d, *n0 = mont->n0;
819 int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
823 * BN_to_montgomery can contaminate words above .top [in
824 * BN_DEBUG[_DEBUG] build]...
826 for (i = am.top; i < top; i++)
828 for (i = tmp.top; i < top; i++)
831 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
832 bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
833 if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
834 !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
835 bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
836 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
838 for (i = 3; i < 32; i++) {
839 /* Calculate a^i = a^(i-1) * a */
840 if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
841 !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
842 bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
843 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
846 /* switch to 64-bit domain */
847 np = alloca(top * sizeof(BN_ULONG));
849 bn_flip_t4(np, mont->N.d, top);
852 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
853 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
854 bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
857 * Scan the exponent one window at a time starting from the most
864 wvalue = bn_get_bits(p, bits + 1);
866 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
868 /* retry once and fall back */
869 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
873 wvalue >>= stride - 5;
875 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
876 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
877 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
878 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
879 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
880 bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
884 bn_flip_t4(tmp.d, tmp.d, top);
886 /* back to 32-bit domain */
888 bn_correct_top(&tmp);
889 OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
892 #if defined(OPENSSL_BN_ASM_MONT5)
893 if (window == 5 && top > 1) {
895 * This optimization uses ideas from http://eprint.iacr.org/2011/239,
896 * specifically optimization of cache-timing attack countermeasures
897 * and pre-computation optimization.
901 * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
902 * 512-bit RSA is hardly relevant, we omit it to spare size...
904 void bn_mul_mont_gather5(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 void bn_scatter5(const BN_ULONG *inp, size_t num,
908 void *table, size_t power);
909 void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
910 void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
911 const void *table, const BN_ULONG *np,
912 const BN_ULONG *n0, int num, int power);
913 int bn_get_bits5(const BN_ULONG *ap, int off);
914 int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
915 const BN_ULONG *not_used, const BN_ULONG *np,
916 const BN_ULONG *n0, int num);
918 BN_ULONG *n0 = mont->n0, *np;
921 * BN_to_montgomery can contaminate words above .top [in
922 * BN_DEBUG[_DEBUG] build]...
924 for (i = am.top; i < top; i++)
926 for (i = tmp.top; i < top; i++)
930 * copy mont->N.d[] to improve cache locality
932 for (np = am.d + top, i = 0; i < top; i++)
933 np[i] = mont->N.d[i];
935 bn_scatter5(tmp.d, top, powerbuf, 0);
936 bn_scatter5(am.d, am.top, powerbuf, 1);
937 bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
938 bn_scatter5(tmp.d, top, powerbuf, 2);
941 for (i = 3; i < 32; i++) {
942 /* Calculate a^i = a^(i-1) * a */
943 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
944 bn_scatter5(tmp.d, top, powerbuf, i);
947 /* same as above, but uses squaring for 1/2 of operations */
948 for (i = 4; i < 32; i *= 2) {
949 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
950 bn_scatter5(tmp.d, top, powerbuf, i);
952 for (i = 3; i < 8; i += 2) {
954 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
955 bn_scatter5(tmp.d, top, powerbuf, i);
956 for (j = 2 * i; j < 32; j *= 2) {
957 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
958 bn_scatter5(tmp.d, top, powerbuf, j);
961 for (; i < 16; 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);
964 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
965 bn_scatter5(tmp.d, top, powerbuf, 2 * i);
967 for (; i < 32; i += 2) {
968 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
969 bn_scatter5(tmp.d, top, powerbuf, i);
973 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
974 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
975 bn_gather5(tmp.d, top, powerbuf, wvalue);
978 * Scan the exponent one window at a time starting from the most
983 for (wvalue = 0, i = 0; i < 5; i++, bits--)
984 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
986 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
987 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
988 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
989 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
990 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
991 bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
995 wvalue = bn_get_bits5(p->d, bits - 4);
997 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
1001 ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
1003 bn_correct_top(&tmp);
1005 if (!BN_copy(rr, &tmp))
1007 goto err; /* non-zero ret means it's not error */
1012 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
1014 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
1018 * If the window size is greater than 1, then calculate
1019 * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
1020 * powers could instead be computed as (a^(i/2))^2 to use the slight
1021 * performance advantage of sqr over mul).
1024 if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
1026 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
1029 for (i = 3; i < numPowers; i++) {
1030 /* Calculate a^i = a^(i-1) * a */
1031 if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
1033 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
1040 for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
1041 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1042 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
1047 * Scan the exponent one window at a time starting from the most
1051 wvalue = 0; /* The 'value' of the window */
1053 /* Scan the window, squaring the result as we go */
1054 for (i = 0; i < window; i++, bits--) {
1055 if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
1057 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1061 * Fetch the appropriate pre-computed value from the pre-buf
1063 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
1067 /* Multiply the result into the intermediate result */
1068 if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
1073 /* Convert the final result from montgomery to standard format */
1074 #if defined(SPARC_T4_MONT)
1075 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
1076 am.d[0] = 1; /* borrow am */
1077 for (i = 1; i < top; i++)
1079 if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
1083 if (!BN_from_montgomery(rr, &tmp, mont, ctx))
1087 if (in_mont == NULL)
1088 BN_MONT_CTX_free(mont);
1089 if (powerbuf != NULL) {
1090 OPENSSL_cleanse(powerbuf, powerbufLen);
1091 OPENSSL_free(powerbufFree);
1097 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1098 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1100 BN_MONT_CTX *mont = NULL;
1101 int b, bits, ret = 0;
1106 #define BN_MOD_MUL_WORD(r, w, m) \
1107 (BN_mul_word(r, (w)) && \
1108 (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
1109 (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
1111 * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
1112 * probably more overhead than always using BN_mod (which uses BN_copy if
1113 * a similar test returns true).
1116 * We can use BN_mod and do not need BN_nnmod because our accumulator is
1117 * never negative (the result of BN_mod does not depend on the sign of
1120 #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
1121 (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
1123 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
1124 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
1125 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1126 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1133 if (!BN_is_odd(m)) {
1134 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
1138 a %= m->d[0]; /* make sure that 'a' is reduced */
1140 bits = BN_num_bits(p);
1142 /* x**0 mod 1 is still zero. */
1158 r = BN_CTX_get(ctx);
1159 t = BN_CTX_get(ctx);
1163 if (in_mont != NULL)
1166 if ((mont = BN_MONT_CTX_new()) == NULL)
1168 if (!BN_MONT_CTX_set(mont, m, ctx))
1172 r_is_one = 1; /* except for Montgomery factor */
1176 /* The result is accumulated in the product r*w. */
1177 w = a; /* bit 'bits-1' of 'p' is always set */
1178 for (b = bits - 2; b >= 0; b--) {
1179 /* First, square r*w. */
1181 if ((next_w / w) != w) { /* overflow */
1183 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1187 if (!BN_MOD_MUL_WORD(r, w, m))
1194 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
1198 /* Second, multiply r*w by 'a' if exponent bit is set. */
1199 if (BN_is_bit_set(p, b)) {
1201 if ((next_w / a) != w) { /* overflow */
1203 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1207 if (!BN_MOD_MUL_WORD(r, w, m))
1216 /* Finally, set r:=r*w. */
1219 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1223 if (!BN_MOD_MUL_WORD(r, w, m))
1228 if (r_is_one) { /* can happen only if a == 1 */
1232 if (!BN_from_montgomery(rr, r, mont, ctx))
1237 if (in_mont == NULL)
1238 BN_MONT_CTX_free(mont);
1244 /* The old fallback, simple version :-) */
1245 int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1246 const BIGNUM *m, BN_CTX *ctx)
1248 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
1251 /* Table of variables obtained from 'ctx' */
1252 BIGNUM *val[TABLE_SIZE];
1254 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
1255 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
1256 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
1257 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1258 BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1262 bits = BN_num_bits(p);
1264 /* x**0 mod 1 is still zero. */
1275 d = BN_CTX_get(ctx);
1276 val[0] = BN_CTX_get(ctx);
1280 if (!BN_nnmod(val[0], a, m, ctx))
1282 if (BN_is_zero(val[0])) {
1288 window = BN_window_bits_for_exponent_size(bits);
1290 if (!BN_mod_mul(d, val[0], val[0], m, ctx))
1292 j = 1 << (window - 1);
1293 for (i = 1; i < j; i++) {
1294 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
1295 !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
1300 start = 1; /* This is used to avoid multiplication etc
1301 * when there is only the value '1' in the
1303 wvalue = 0; /* The 'value' of the window */
1304 wstart = bits - 1; /* The top bit of the window */
1305 wend = 0; /* The bottom bit of the window */
1311 if (BN_is_bit_set(p, wstart) == 0) {
1313 if (!BN_mod_mul(r, r, r, m, ctx))
1321 * We now have wstart on a 'set' bit, we now need to work out how bit
1322 * a window to do. To do this we need to scan forward until the last
1323 * set bit before the end of the window
1328 for (i = 1; i < window; i++) {
1331 if (BN_is_bit_set(p, wstart - i)) {
1332 wvalue <<= (i - wend);
1338 /* wend is the size of the current window */
1340 /* add the 'bytes above' */
1342 for (i = 0; i < j; i++) {
1343 if (!BN_mod_mul(r, r, r, m, ctx))
1347 /* wvalue will be an odd number < 2^window */
1348 if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
1351 /* move the 'window' down further */