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 * I have finally been able to take out this pre-condition of the top bit
138 * being set. It was caused by an error in BN_div with negatives. There
139 * was also another problem when for a^b%m a >= m. eay 07-May-97
141 /* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */
144 # ifdef MONT_EXP_WORD
145 if (a->top == 1 && !a->neg
146 && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)) {
147 BN_ULONG A = a->d[0];
148 ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
151 ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
156 ret = BN_mod_exp_recp(r, a, p, m, ctx);
160 ret = BN_mod_exp_simple(r, a, p, m, ctx);
168 int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
169 const BIGNUM *m, BN_CTX *ctx)
171 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
174 /* Table of variables obtained from 'ctx' */
175 BIGNUM *val[TABLE_SIZE];
178 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
179 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
180 BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
184 bits = BN_num_bits(p);
186 /* x**0 mod 1 is still zero. */
197 aa = BN_CTX_get(ctx);
198 val[0] = BN_CTX_get(ctx);
202 BN_RECP_CTX_init(&recp);
204 /* ignore sign of 'm' */
208 if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
211 if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
215 if (!BN_nnmod(val[0], a, m, ctx))
217 if (BN_is_zero(val[0])) {
223 window = BN_window_bits_for_exponent_size(bits);
225 if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
227 j = 1 << (window - 1);
228 for (i = 1; i < j; i++) {
229 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
230 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
235 start = 1; /* This is used to avoid multiplication etc
236 * when there is only the value '1' in the
238 wvalue = 0; /* The 'value' of the window */
239 wstart = bits - 1; /* The top bit of the window */
240 wend = 0; /* The bottom bit of the window */
246 if (BN_is_bit_set(p, wstart) == 0) {
248 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
256 * We now have wstart on a 'set' bit, we now need to work out how bit
257 * a window to do. To do this we need to scan forward until the last
258 * set bit before the end of the window
263 for (i = 1; i < window; i++) {
266 if (BN_is_bit_set(p, wstart - i)) {
267 wvalue <<= (i - wend);
273 /* wend is the size of the current window */
275 /* add the 'bytes above' */
277 for (i = 0; i < j; i++) {
278 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
282 /* wvalue will be an odd number < 2^window */
283 if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
286 /* move the 'window' down further */
296 BN_RECP_CTX_free(&recp);
301 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
302 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
304 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
308 /* Table of variables obtained from 'ctx' */
309 BIGNUM *val[TABLE_SIZE];
310 BN_MONT_CTX *mont = NULL;
312 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
313 return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
321 BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
324 bits = BN_num_bits(p);
326 /* x**0 mod 1 is still zero. */
339 val[0] = BN_CTX_get(ctx);
340 if (!d || !r || !val[0])
344 * If this is not done, things will break in the montgomery part
350 if ((mont = BN_MONT_CTX_new()) == NULL)
352 if (!BN_MONT_CTX_set(mont, m, ctx))
356 if (a->neg || BN_ucmp(a, m) >= 0) {
357 if (!BN_nnmod(val[0], a, m, ctx))
362 if (BN_is_zero(aa)) {
367 if (!BN_to_montgomery(val[0], aa, mont, ctx))
370 window = BN_window_bits_for_exponent_size(bits);
372 if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
374 j = 1 << (window - 1);
375 for (i = 1; i < j; i++) {
376 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
377 !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
382 start = 1; /* This is used to avoid multiplication etc
383 * when there is only the value '1' in the
385 wvalue = 0; /* The 'value' of the window */
386 wstart = bits - 1; /* The top bit of the window */
387 wend = 0; /* The bottom bit of the window */
389 #if 1 /* by Shay Gueron's suggestion */
390 j = m->top; /* borrow j */
391 if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
392 if (bn_wexpand(r, j) == NULL)
394 /* 2^(top*BN_BITS2) - m */
395 r->d[0] = (0 - m->d[0]) & BN_MASK2;
396 for (i = 1; i < j; i++)
397 r->d[i] = (~m->d[i]) & BN_MASK2;
400 * Upper words will be zero if the corresponding words of 'm' were
401 * 0xfff[...], so decrement r->top accordingly.
406 if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
409 if (BN_is_bit_set(p, wstart) == 0) {
411 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
420 * We now have wstart on a 'set' bit, we now need to work out how bit
421 * a window to do. To do this we need to scan forward until the last
422 * set bit before the end of the window
427 for (i = 1; i < window; i++) {
430 if (BN_is_bit_set(p, wstart - i)) {
431 wvalue <<= (i - wend);
437 /* wend is the size of the current window */
439 /* add the 'bytes above' */
441 for (i = 0; i < j; i++) {
442 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
446 /* wvalue will be an odd number < 2^window */
447 if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
450 /* move the 'window' down further */
457 #if defined(SPARC_T4_MONT)
458 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
459 j = mont->N.top; /* borrow j */
460 val[0]->d[0] = 1; /* borrow val[0] */
461 for (i = 1; i < j; i++)
464 if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
468 if (!BN_from_montgomery(rr, r, mont, ctx))
473 BN_MONT_CTX_free(mont);
479 #if defined(SPARC_T4_MONT)
480 static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
485 wordpos = bitpos / BN_BITS2;
487 if (wordpos >= 0 && wordpos < a->top) {
488 ret = a->d[wordpos] & BN_MASK2;
491 if (++wordpos < a->top)
492 ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
496 return ret & BN_MASK2;
501 * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
502 * layout so that accessing any of these table values shows the same access
503 * pattern as far as cache lines are concerned. The following functions are
504 * used to transfer a BIGNUM from/to that table.
507 static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
508 unsigned char *buf, int idx,
512 int width = 1 << window;
513 BN_ULONG *table = (BN_ULONG *)buf;
516 top = b->top; /* this works because 'buf' is explicitly
518 for (i = 0, j = idx; i < top; i++, j += width) {
525 static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
526 unsigned char *buf, int idx,
530 int width = 1 << window;
532 * We declare table 'volatile' in order to discourage compiler
533 * from reordering loads from the table. Concern is that if
534 * reordered in specific manner loads might give away the
535 * information we are trying to conceal. Some would argue that
536 * compiler can reorder them anyway, but it can as well be
537 * argued that doing so would be violation of standard...
539 volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
541 if (bn_wexpand(b, top) == NULL)
545 for (i = 0; i < top; i++, table += width) {
548 for (j = 0; j < width; j++) {
550 ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
556 int xstride = 1 << (window - 2);
557 BN_ULONG y0, y1, y2, y3;
559 i = idx >> (window - 2); /* equivalent of idx / xstride */
560 idx &= xstride - 1; /* equivalent of idx % xstride */
562 y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
563 y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
564 y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
565 y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
567 for (i = 0; i < top; i++, table += width) {
570 for (j = 0; j < xstride; j++) {
571 acc |= ( (table[j + 0 * xstride] & y0) |
572 (table[j + 1 * xstride] & y1) |
573 (table[j + 2 * xstride] & y2) |
574 (table[j + 3 * xstride] & y3) )
575 & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
588 * Given a pointer value, compute the next address that is a cache line
591 #define MOD_EXP_CTIME_ALIGN(x_) \
592 ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
595 * This variant of BN_mod_exp_mont() uses fixed windows and the special
596 * precomputation memory layout to limit data-dependency to a minimum to
597 * protect secret exponents (cf. the hyper-threading timing attacks pointed
598 * out by Colin Percival,
599 * http://www.daemonology.net/hyperthreading-considered-harmful/)
601 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
602 const BIGNUM *m, BN_CTX *ctx,
603 BN_MONT_CTX *in_mont)
605 int i, bits, ret = 0, window, wvalue;
607 BN_MONT_CTX *mont = NULL;
610 unsigned char *powerbufFree = NULL;
612 unsigned char *powerbuf = NULL;
614 #if defined(SPARC_T4_MONT)
623 BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
629 bits = BN_num_bits(p);
631 /* x**0 mod 1 is still zero. */
644 * Allocate a montgomery context if it was not supplied by the caller. If
645 * this is not done, things will break in the montgomery part.
650 if ((mont = BN_MONT_CTX_new()) == NULL)
652 if (!BN_MONT_CTX_set(mont, m, ctx))
658 * If the size of the operands allow it, perform the optimized
659 * RSAZ exponentiation. For further information see
660 * crypto/bn/rsaz_exp.c and accompanying assembly modules.
662 if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
663 && rsaz_avx2_eligible()) {
664 if (NULL == bn_wexpand(rr, 16))
666 RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
673 } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
674 if (NULL == bn_wexpand(rr, 8))
676 RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
685 /* Get the window size to use with size of p. */
686 window = BN_window_bits_for_ctime_exponent_size(bits);
687 #if defined(SPARC_T4_MONT)
688 if (window >= 5 && (top & 15) == 0 && top <= 64 &&
689 (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
690 (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
694 #if defined(OPENSSL_BN_ASM_MONT5)
696 window = 5; /* ~5% improvement for RSA2048 sign, and even
698 /* reserve space for mont->N.d[] copy */
699 powerbufLen += top * sizeof(mont->N.d[0]);
705 * Allocate a buffer large enough to hold all of the pre-computed powers
706 * of am, am itself and tmp.
708 numPowers = 1 << window;
709 powerbufLen += sizeof(m->d[0]) * (top * numPowers +
711 numPowers ? (2 * top) : numPowers));
713 if (powerbufLen < 3072)
715 alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
719 OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
723 powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
724 memset(powerbuf, 0, powerbufLen);
727 if (powerbufLen < 3072)
731 /* lay down tmp and am right after powers table */
732 tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
734 tmp.top = am.top = 0;
735 tmp.dmax = am.dmax = top;
736 tmp.neg = am.neg = 0;
737 tmp.flags = am.flags = BN_FLG_STATIC_DATA;
739 /* prepare a^0 in Montgomery domain */
740 #if 1 /* by Shay Gueron's suggestion */
741 if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
742 /* 2^(top*BN_BITS2) - m */
743 tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
744 for (i = 1; i < top; i++)
745 tmp.d[i] = (~m->d[i]) & BN_MASK2;
749 if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
752 /* prepare a^1 in Montgomery domain */
753 if (a->neg || BN_ucmp(a, m) >= 0) {
754 if (!BN_mod(&am, a, m, ctx))
756 if (!BN_to_montgomery(&am, &am, mont, ctx))
758 } else if (!BN_to_montgomery(&am, a, mont, ctx))
761 #if defined(SPARC_T4_MONT)
763 typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
764 const BN_ULONG *n0, const void *table,
765 int power, int bits);
766 int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
767 const BN_ULONG *n0, const void *table,
768 int power, int bits);
769 int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
770 const BN_ULONG *n0, const void *table,
771 int power, int bits);
772 int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
773 const BN_ULONG *n0, const void *table,
774 int power, int bits);
775 int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
776 const BN_ULONG *n0, const void *table,
777 int power, int bits);
778 static const bn_pwr5_mont_f pwr5_funcs[4] = {
779 bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
780 bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
782 bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
784 typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
785 const void *bp, const BN_ULONG *np,
787 int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
788 const BN_ULONG *np, const BN_ULONG *n0);
789 int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
790 const void *bp, const BN_ULONG *np,
792 int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
793 const void *bp, const BN_ULONG *np,
795 int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
796 const void *bp, const BN_ULONG *np,
798 static const bn_mul_mont_f mul_funcs[4] = {
799 bn_mul_mont_t4_8, bn_mul_mont_t4_16,
800 bn_mul_mont_t4_24, bn_mul_mont_t4_32
802 bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
804 void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
805 const void *bp, const BN_ULONG *np,
806 const BN_ULONG *n0, int num);
807 void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
808 const void *bp, const BN_ULONG *np,
809 const BN_ULONG *n0, int num);
810 void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
811 const void *table, const BN_ULONG *np,
812 const BN_ULONG *n0, int num, int power);
813 void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
814 void *table, size_t power);
815 void bn_gather5_t4(BN_ULONG *out, size_t num,
816 void *table, size_t power);
817 void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
819 BN_ULONG *np = mont->N.d, *n0 = mont->n0;
820 int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
824 * BN_to_montgomery can contaminate words above .top [in
825 * BN_DEBUG[_DEBUG] build]...
827 for (i = am.top; i < top; i++)
829 for (i = tmp.top; i < top; i++)
832 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
833 bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
834 if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
835 !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
836 bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
837 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
839 for (i = 3; i < 32; i++) {
840 /* Calculate a^i = a^(i-1) * a */
841 if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
842 !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
843 bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
844 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
847 /* switch to 64-bit domain */
848 np = alloca(top * sizeof(BN_ULONG));
850 bn_flip_t4(np, mont->N.d, top);
853 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
854 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
855 bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
858 * Scan the exponent one window at a time starting from the most
865 wvalue = bn_get_bits(p, bits + 1);
867 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
869 /* retry once and fall back */
870 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
874 wvalue >>= stride - 5;
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_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
881 bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
885 bn_flip_t4(tmp.d, tmp.d, top);
887 /* back to 32-bit domain */
889 bn_correct_top(&tmp);
890 OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
893 #if defined(OPENSSL_BN_ASM_MONT5)
894 if (window == 5 && top > 1) {
896 * This optimization uses ideas from http://eprint.iacr.org/2011/239,
897 * specifically optimization of cache-timing attack countermeasures
898 * and pre-computation optimization.
902 * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
903 * 512-bit RSA is hardly relevant, we omit it to spare size...
905 void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
906 const void *table, const BN_ULONG *np,
907 const BN_ULONG *n0, int num, int power);
908 void bn_scatter5(const BN_ULONG *inp, size_t num,
909 void *table, size_t power);
910 void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
911 void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
912 const void *table, const BN_ULONG *np,
913 const BN_ULONG *n0, int num, int power);
914 int bn_get_bits5(const BN_ULONG *ap, int off);
915 int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
916 const BN_ULONG *not_used, const BN_ULONG *np,
917 const BN_ULONG *n0, int num);
919 BN_ULONG *n0 = mont->n0, *np;
922 * BN_to_montgomery can contaminate words above .top [in
923 * BN_DEBUG[_DEBUG] build]...
925 for (i = am.top; i < top; i++)
927 for (i = tmp.top; i < top; i++)
931 * copy mont->N.d[] to improve cache locality
933 for (np = am.d + top, i = 0; i < top; i++)
934 np[i] = mont->N.d[i];
936 bn_scatter5(tmp.d, top, powerbuf, 0);
937 bn_scatter5(am.d, am.top, powerbuf, 1);
938 bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
939 bn_scatter5(tmp.d, top, powerbuf, 2);
942 for (i = 3; i < 32; i++) {
943 /* Calculate a^i = a^(i-1) * a */
944 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
945 bn_scatter5(tmp.d, top, powerbuf, i);
948 /* same as above, but uses squaring for 1/2 of operations */
949 for (i = 4; i < 32; i *= 2) {
950 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
951 bn_scatter5(tmp.d, top, powerbuf, i);
953 for (i = 3; i < 8; i += 2) {
955 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
956 bn_scatter5(tmp.d, top, powerbuf, i);
957 for (j = 2 * i; j < 32; j *= 2) {
958 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
959 bn_scatter5(tmp.d, top, powerbuf, j);
962 for (; i < 16; i += 2) {
963 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
964 bn_scatter5(tmp.d, top, powerbuf, i);
965 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
966 bn_scatter5(tmp.d, top, powerbuf, 2 * i);
968 for (; i < 32; i += 2) {
969 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
970 bn_scatter5(tmp.d, top, powerbuf, i);
974 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
975 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
976 bn_gather5(tmp.d, top, powerbuf, wvalue);
979 * Scan the exponent one window at a time starting from the most
984 for (wvalue = 0, i = 0; i < 5; i++, bits--)
985 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
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(tmp.d, tmp.d, tmp.d, np, n0, top);
992 bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
996 wvalue = bn_get_bits5(p->d, bits - 4);
998 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
1002 ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
1004 bn_correct_top(&tmp);
1006 if (!BN_copy(rr, &tmp))
1008 goto err; /* non-zero ret means it's not error */
1013 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
1015 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
1019 * If the window size is greater than 1, then calculate
1020 * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
1021 * powers could instead be computed as (a^(i/2))^2 to use the slight
1022 * performance advantage of sqr over mul).
1025 if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
1027 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
1030 for (i = 3; i < numPowers; i++) {
1031 /* Calculate a^i = a^(i-1) * a */
1032 if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
1034 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
1041 for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
1042 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1043 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
1048 * Scan the exponent one window at a time starting from the most
1052 wvalue = 0; /* The 'value' of the window */
1054 /* Scan the window, squaring the result as we go */
1055 for (i = 0; i < window; i++, bits--) {
1056 if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
1058 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1062 * Fetch the appropriate pre-computed value from the pre-buf
1064 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
1068 /* Multiply the result into the intermediate result */
1069 if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
1074 /* Convert the final result from montgomery to standard format */
1075 #if defined(SPARC_T4_MONT)
1076 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
1077 am.d[0] = 1; /* borrow am */
1078 for (i = 1; i < top; i++)
1080 if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
1084 if (!BN_from_montgomery(rr, &tmp, mont, ctx))
1088 if (in_mont == NULL)
1089 BN_MONT_CTX_free(mont);
1090 if (powerbuf != NULL) {
1091 OPENSSL_cleanse(powerbuf, powerbufLen);
1092 OPENSSL_free(powerbufFree);
1098 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1099 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1101 BN_MONT_CTX *mont = NULL;
1102 int b, bits, ret = 0;
1107 #define BN_MOD_MUL_WORD(r, w, m) \
1108 (BN_mul_word(r, (w)) && \
1109 (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
1110 (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
1112 * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
1113 * probably more overhead than always using BN_mod (which uses BN_copy if
1114 * a similar test returns true).
1117 * We can use BN_mod and do not need BN_nnmod because our accumulator is
1118 * never negative (the result of BN_mod does not depend on the sign of
1121 #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
1122 (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
1124 if (BN_get_flags(p, 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 d = BN_CTX_get(ctx);
1159 r = BN_CTX_get(ctx);
1160 t = BN_CTX_get(ctx);
1161 if (d == NULL || r == NULL || t == NULL)
1164 if (in_mont != NULL)
1167 if ((mont = BN_MONT_CTX_new()) == NULL)
1169 if (!BN_MONT_CTX_set(mont, m, ctx))
1173 r_is_one = 1; /* except for Montgomery factor */
1177 /* The result is accumulated in the product r*w. */
1178 w = a; /* bit 'bits-1' of 'p' is always set */
1179 for (b = bits - 2; b >= 0; b--) {
1180 /* First, square r*w. */
1182 if ((next_w / w) != w) { /* overflow */
1184 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1188 if (!BN_MOD_MUL_WORD(r, w, m))
1195 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
1199 /* Second, multiply r*w by 'a' if exponent bit is set. */
1200 if (BN_is_bit_set(p, b)) {
1202 if ((next_w / a) != w) { /* overflow */
1204 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1208 if (!BN_MOD_MUL_WORD(r, w, m))
1217 /* Finally, set r:=r*w. */
1220 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1224 if (!BN_MOD_MUL_WORD(r, w, m))
1229 if (r_is_one) { /* can happen only if a == 1 */
1233 if (!BN_from_montgomery(rr, r, mont, ctx))
1238 if (in_mont == NULL)
1239 BN_MONT_CTX_free(mont);
1245 /* The old fallback, simple version :-) */
1246 int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1247 const BIGNUM *m, BN_CTX *ctx)
1249 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
1252 /* Table of variables obtained from 'ctx' */
1253 BIGNUM *val[TABLE_SIZE];
1255 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
1256 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1257 BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1261 bits = BN_num_bits(p);
1263 /* x**0 mod 1 is still zero. */
1274 d = BN_CTX_get(ctx);
1275 val[0] = BN_CTX_get(ctx);
1279 if (!BN_nnmod(val[0], a, m, ctx))
1281 if (BN_is_zero(val[0])) {
1287 window = BN_window_bits_for_exponent_size(bits);
1289 if (!BN_mod_mul(d, val[0], val[0], m, ctx))
1291 j = 1 << (window - 1);
1292 for (i = 1; i < j; i++) {
1293 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
1294 !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
1299 start = 1; /* This is used to avoid multiplication etc
1300 * when there is only the value '1' in the
1302 wvalue = 0; /* The 'value' of the window */
1303 wstart = bits - 1; /* The top bit of the window */
1304 wend = 0; /* The bottom bit of the window */
1310 if (BN_is_bit_set(p, wstart) == 0) {
1312 if (!BN_mod_mul(r, r, r, m, ctx))
1320 * We now have wstart on a 'set' bit, we now need to work out how bit
1321 * a window to do. To do this we need to scan forward until the last
1322 * set bit before the end of the window
1327 for (i = 1; i < window; i++) {
1330 if (BN_is_bit_set(p, wstart - i)) {
1331 wvalue <<= (i - wend);
1337 /* wend is the size of the current window */
1339 /* add the 'bytes above' */
1341 for (i = 0; i < j; i++) {
1342 if (!BN_mod_mul(r, r, r, m, ctx))
1346 /* wvalue will be an odd number < 2^window */
1347 if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
1350 /* move the 'window' down further */