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))
90 int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
100 * For even modulus m = 2^k*m_odd, it might make sense to compute
101 * a^p mod m_odd and a^p mod 2^k separately (with Montgomery
102 * exponentiation for the odd part), using appropriate exponent
103 * reductions, and combine the results using the CRT.
105 * For now, we use Montgomery only if the modulus is odd; otherwise,
106 * exponentiation using the reciprocal-based quick remaindering
109 * (Timing obtained with expspeed.c [computations a^p mod m
110 * where a, p, m are of the same length: 256, 512, 1024, 2048,
111 * 4096, 8192 bits], compared to the running time of the
112 * standard algorithm:
114 * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration]
115 * 55 .. 77 % [UltraSparc processor, but
116 * debug-solaris-sparcv8-gcc conf.]
118 * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
119 * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
121 * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
122 * at 2048 and more bits, but at 512 and 1024 bits, it was
123 * slower even than the standard algorithm!
125 * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
126 * should be obtained when the new Montgomery reduction code
127 * has been integrated into OpenSSL.)
131 #define MONT_EXP_WORD
136 * I have finally been able to take out this pre-condition of the top bit
137 * being set. It was caused by an error in BN_div with negatives. There
138 * was also another problem when for a^b%m a >= m. eay 07-May-97
140 /* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */
143 # ifdef MONT_EXP_WORD
144 if (a->top == 1 && !a->neg
145 && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)) {
146 BN_ULONG A = a->d[0];
147 ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
150 ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
155 ret = BN_mod_exp_recp(r, a, p, m, ctx);
159 ret = BN_mod_exp_simple(r, a, p, m, ctx);
167 int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
168 const BIGNUM *m, BN_CTX *ctx)
170 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
173 /* Table of variables obtained from 'ctx' */
174 BIGNUM *val[TABLE_SIZE];
177 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
178 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
179 BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
183 bits = BN_num_bits(p);
185 /* x**0 mod 1 is still zero. */
196 aa = BN_CTX_get(ctx);
197 val[0] = BN_CTX_get(ctx);
201 BN_RECP_CTX_init(&recp);
203 /* ignore sign of 'm' */
207 if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
210 if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
214 if (!BN_nnmod(val[0], a, m, ctx))
216 if (BN_is_zero(val[0])) {
222 window = BN_window_bits_for_exponent_size(bits);
224 if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
226 j = 1 << (window - 1);
227 for (i = 1; i < j; i++) {
228 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
229 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
234 start = 1; /* This is used to avoid multiplication etc
235 * when there is only the value '1' in the
237 wvalue = 0; /* The 'value' of the window */
238 wstart = bits - 1; /* The top bit of the window */
239 wend = 0; /* The bottom bit of the window */
245 if (BN_is_bit_set(p, wstart) == 0) {
247 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
255 * We now have wstart on a 'set' bit, we now need to work out how bit
256 * a window to do. To do this we need to scan forward until the last
257 * set bit before the end of the window
262 for (i = 1; i < window; i++) {
265 if (BN_is_bit_set(p, wstart - i)) {
266 wvalue <<= (i - wend);
272 /* wend is the size of the current window */
274 /* add the 'bytes above' */
276 for (i = 0; i < j; i++) {
277 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
281 /* wvalue will be an odd number < 2^window */
282 if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
285 /* move the 'window' down further */
295 BN_RECP_CTX_free(&recp);
300 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
301 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
303 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
307 /* Table of variables obtained from 'ctx' */
308 BIGNUM *val[TABLE_SIZE];
309 BN_MONT_CTX *mont = NULL;
311 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
312 return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
320 BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
323 bits = BN_num_bits(p);
325 /* x**0 mod 1 is still zero. */
338 val[0] = BN_CTX_get(ctx);
339 if (!d || !r || !val[0])
343 * If this is not done, things will break in the montgomery part
349 if ((mont = BN_MONT_CTX_new()) == NULL)
351 if (!BN_MONT_CTX_set(mont, m, ctx))
355 if (a->neg || BN_ucmp(a, m) >= 0) {
356 if (!BN_nnmod(val[0], a, m, ctx))
361 if (BN_is_zero(aa)) {
366 if (!BN_to_montgomery(val[0], aa, mont, ctx))
369 window = BN_window_bits_for_exponent_size(bits);
371 if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
373 j = 1 << (window - 1);
374 for (i = 1; i < j; i++) {
375 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
376 !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
381 start = 1; /* This is used to avoid multiplication etc
382 * when there is only the value '1' in the
384 wvalue = 0; /* The 'value' of the window */
385 wstart = bits - 1; /* The top bit of the window */
386 wend = 0; /* The bottom bit of the window */
388 #if 1 /* by Shay Gueron's suggestion */
389 j = m->top; /* borrow j */
390 if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
391 if (bn_wexpand(r, j) == NULL)
393 /* 2^(top*BN_BITS2) - m */
394 r->d[0] = (0 - m->d[0]) & BN_MASK2;
395 for (i = 1; i < j; i++)
396 r->d[i] = (~m->d[i]) & BN_MASK2;
399 * Upper words will be zero if the corresponding words of 'm' were
400 * 0xfff[...], so decrement r->top accordingly.
405 if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
408 if (BN_is_bit_set(p, wstart) == 0) {
410 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
419 * We now have wstart on a 'set' bit, we now need to work out how bit
420 * a window to do. To do this we need to scan forward until the last
421 * set bit before the end of the window
426 for (i = 1; i < window; i++) {
429 if (BN_is_bit_set(p, wstart - i)) {
430 wvalue <<= (i - wend);
436 /* wend is the size of the current window */
438 /* add the 'bytes above' */
440 for (i = 0; i < j; i++) {
441 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
445 /* wvalue will be an odd number < 2^window */
446 if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
449 /* move the 'window' down further */
456 #if defined(SPARC_T4_MONT)
457 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
458 j = mont->N.top; /* borrow j */
459 val[0]->d[0] = 1; /* borrow val[0] */
460 for (i = 1; i < j; i++)
463 if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
467 if (!BN_from_montgomery(rr, r, mont, ctx))
472 BN_MONT_CTX_free(mont);
478 #if defined(SPARC_T4_MONT)
479 static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
484 wordpos = bitpos / BN_BITS2;
486 if (wordpos >= 0 && wordpos < a->top) {
487 ret = a->d[wordpos] & BN_MASK2;
490 if (++wordpos < a->top)
491 ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
495 return ret & BN_MASK2;
500 * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
501 * layout so that accessing any of these table values shows the same access
502 * pattern as far as cache lines are concerned. The following functions are
503 * used to transfer a BIGNUM from/to that table.
506 static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
507 unsigned char *buf, int idx,
511 int width = 1 << window;
512 BN_ULONG *table = (BN_ULONG *)buf;
515 top = b->top; /* this works because 'buf' is explicitly
517 for (i = 0, j = idx; i < top; i++, j += width) {
524 static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
525 unsigned char *buf, int idx,
529 int width = 1 << window;
530 volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
532 if (bn_wexpand(b, top) == NULL)
536 for (i = 0; i < top; i++, table += width) {
539 for (j = 0; j < width; j++) {
541 ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
547 int xstride = 1 << (window - 2);
548 BN_ULONG y0, y1, y2, y3;
550 i = idx >> (window - 2); /* equivalent of idx / xstride */
551 idx &= xstride - 1; /* equivalent of idx % xstride */
553 y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
554 y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
555 y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
556 y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
558 for (i = 0; i < top; i++, table += width) {
561 for (j = 0; j < xstride; j++) {
562 acc |= ( (table[j + 0 * xstride] & y0) |
563 (table[j + 1 * xstride] & y1) |
564 (table[j + 2 * xstride] & y2) |
565 (table[j + 3 * xstride] & y3) )
566 & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
579 * Given a pointer value, compute the next address that is a cache line
582 #define MOD_EXP_CTIME_ALIGN(x_) \
583 ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
586 * This variant of BN_mod_exp_mont() uses fixed windows and the special
587 * precomputation memory layout to limit data-dependency to a minimum to
588 * protect secret exponents (cf. the hyper-threading timing attacks pointed
589 * out by Colin Percival,
590 * http://www.daemonology.net/hyperthreading-considered-harmful/)
592 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
593 const BIGNUM *m, BN_CTX *ctx,
594 BN_MONT_CTX *in_mont)
596 int i, bits, ret = 0, window, wvalue;
598 BN_MONT_CTX *mont = NULL;
601 unsigned char *powerbufFree = NULL;
603 unsigned char *powerbuf = NULL;
605 #if defined(SPARC_T4_MONT)
614 BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
620 bits = BN_num_bits(p);
622 /* x**0 mod 1 is still zero. */
635 * Allocate a montgomery context if it was not supplied by the caller. If
636 * this is not done, things will break in the montgomery part.
641 if ((mont = BN_MONT_CTX_new()) == NULL)
643 if (!BN_MONT_CTX_set(mont, m, ctx))
649 * If the size of the operands allow it, perform the optimized
650 * RSAZ exponentiation. For further information see
651 * crypto/bn/rsaz_exp.c and accompanying assembly modules.
653 if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
654 && rsaz_avx2_eligible()) {
655 if (NULL == bn_wexpand(rr, 16))
657 RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
664 } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
665 if (NULL == bn_wexpand(rr, 8))
667 RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
676 /* Get the window size to use with size of p. */
677 window = BN_window_bits_for_ctime_exponent_size(bits);
678 #if defined(SPARC_T4_MONT)
679 if (window >= 5 && (top & 15) == 0 && top <= 64 &&
680 (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
681 (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
685 #if defined(OPENSSL_BN_ASM_MONT5)
687 window = 5; /* ~5% improvement for RSA2048 sign, and even
689 /* reserve space for mont->N.d[] copy */
690 powerbufLen += top * sizeof(mont->N.d[0]);
696 * Allocate a buffer large enough to hold all of the pre-computed powers
697 * of am, am itself and tmp.
699 numPowers = 1 << window;
700 powerbufLen += sizeof(m->d[0]) * (top * numPowers +
702 numPowers ? (2 * top) : numPowers));
704 if (powerbufLen < 3072)
706 alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
710 OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
714 powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
715 memset(powerbuf, 0, powerbufLen);
718 if (powerbufLen < 3072)
722 /* lay down tmp and am right after powers table */
723 tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
725 tmp.top = am.top = 0;
726 tmp.dmax = am.dmax = top;
727 tmp.neg = am.neg = 0;
728 tmp.flags = am.flags = BN_FLG_STATIC_DATA;
730 /* prepare a^0 in Montgomery domain */
731 #if 1 /* by Shay Gueron's suggestion */
732 if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
733 /* 2^(top*BN_BITS2) - m */
734 tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
735 for (i = 1; i < top; i++)
736 tmp.d[i] = (~m->d[i]) & BN_MASK2;
740 if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
743 /* prepare a^1 in Montgomery domain */
744 if (a->neg || BN_ucmp(a, m) >= 0) {
745 if (!BN_mod(&am, a, m, ctx))
747 if (!BN_to_montgomery(&am, &am, mont, ctx))
749 } else if (!BN_to_montgomery(&am, a, mont, ctx))
752 #if defined(SPARC_T4_MONT)
754 typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
755 const BN_ULONG *n0, const void *table,
756 int power, int bits);
757 int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
758 const BN_ULONG *n0, const void *table,
759 int power, int bits);
760 int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
761 const BN_ULONG *n0, const void *table,
762 int power, int bits);
763 int bn_pwr5_mont_t4_24(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_32(BN_ULONG *tp, const BN_ULONG *np,
767 const BN_ULONG *n0, const void *table,
768 int power, int bits);
769 static const bn_pwr5_mont_f pwr5_funcs[4] = {
770 bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
771 bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
773 bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
775 typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
776 const void *bp, const BN_ULONG *np,
778 int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
779 const BN_ULONG *np, const BN_ULONG *n0);
780 int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
781 const void *bp, const BN_ULONG *np,
783 int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
784 const void *bp, const BN_ULONG *np,
786 int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
787 const void *bp, const BN_ULONG *np,
789 static const bn_mul_mont_f mul_funcs[4] = {
790 bn_mul_mont_t4_8, bn_mul_mont_t4_16,
791 bn_mul_mont_t4_24, bn_mul_mont_t4_32
793 bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
795 void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
796 const void *bp, const BN_ULONG *np,
797 const BN_ULONG *n0, int num);
798 void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
799 const void *bp, const BN_ULONG *np,
800 const BN_ULONG *n0, int num);
801 void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
802 const void *table, const BN_ULONG *np,
803 const BN_ULONG *n0, int num, int power);
804 void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
805 void *table, size_t power);
806 void bn_gather5_t4(BN_ULONG *out, size_t num,
807 void *table, size_t power);
808 void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
810 BN_ULONG *np = mont->N.d, *n0 = mont->n0;
811 int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
815 * BN_to_montgomery can contaminate words above .top [in
816 * BN_DEBUG[_DEBUG] build]...
818 for (i = am.top; i < top; i++)
820 for (i = tmp.top; i < top; i++)
823 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
824 bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
825 if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
826 !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
827 bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
828 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
830 for (i = 3; i < 32; i++) {
831 /* Calculate a^i = a^(i-1) * a */
832 if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
833 !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
834 bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
835 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
838 /* switch to 64-bit domain */
839 np = alloca(top * sizeof(BN_ULONG));
841 bn_flip_t4(np, mont->N.d, top);
844 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
845 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
846 bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
849 * Scan the exponent one window at a time starting from the most
856 wvalue = bn_get_bits(p, bits + 1);
858 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
860 /* retry once and fall back */
861 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
865 wvalue >>= stride - 5;
867 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
868 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
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_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
876 bn_flip_t4(tmp.d, tmp.d, top);
878 /* back to 32-bit domain */
880 bn_correct_top(&tmp);
881 OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
884 #if defined(OPENSSL_BN_ASM_MONT5)
885 if (window == 5 && top > 1) {
887 * This optimization uses ideas from http://eprint.iacr.org/2011/239,
888 * specifically optimization of cache-timing attack countermeasures
889 * and pre-computation optimization.
893 * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
894 * 512-bit RSA is hardly relevant, we omit it to spare size...
896 void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
897 const void *table, const BN_ULONG *np,
898 const BN_ULONG *n0, int num, int power);
899 void bn_scatter5(const BN_ULONG *inp, size_t num,
900 void *table, size_t power);
901 void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
902 void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
903 const void *table, const BN_ULONG *np,
904 const BN_ULONG *n0, int num, int power);
905 int bn_get_bits5(const BN_ULONG *ap, int off);
906 int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
907 const BN_ULONG *not_used, const BN_ULONG *np,
908 const BN_ULONG *n0, int num);
910 BN_ULONG *n0 = mont->n0, *np;
913 * BN_to_montgomery can contaminate words above .top [in
914 * BN_DEBUG[_DEBUG] build]...
916 for (i = am.top; i < top; i++)
918 for (i = tmp.top; i < top; i++)
922 * copy mont->N.d[] to improve cache locality
924 for (np = am.d + top, i = 0; i < top; i++)
925 np[i] = mont->N.d[i];
927 bn_scatter5(tmp.d, top, powerbuf, 0);
928 bn_scatter5(am.d, am.top, powerbuf, 1);
929 bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
930 bn_scatter5(tmp.d, top, powerbuf, 2);
933 for (i = 3; i < 32; i++) {
934 /* Calculate a^i = a^(i-1) * a */
935 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
936 bn_scatter5(tmp.d, top, powerbuf, i);
939 /* same as above, but uses squaring for 1/2 of operations */
940 for (i = 4; i < 32; i *= 2) {
941 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
942 bn_scatter5(tmp.d, top, powerbuf, i);
944 for (i = 3; i < 8; i += 2) {
946 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
947 bn_scatter5(tmp.d, top, powerbuf, i);
948 for (j = 2 * i; j < 32; j *= 2) {
949 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
950 bn_scatter5(tmp.d, top, powerbuf, j);
953 for (; i < 16; 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 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
957 bn_scatter5(tmp.d, top, powerbuf, 2 * i);
959 for (; i < 32; i += 2) {
960 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
961 bn_scatter5(tmp.d, top, powerbuf, i);
965 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
966 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
967 bn_gather5(tmp.d, top, powerbuf, wvalue);
970 * Scan the exponent one window at a time starting from the most
975 for (wvalue = 0, i = 0; i < 5; i++, bits--)
976 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
978 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
979 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
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_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
987 wvalue = bn_get_bits5(p->d, bits - 4);
989 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
993 ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
995 bn_correct_top(&tmp);
997 if (!BN_copy(rr, &tmp))
999 goto err; /* non-zero ret means it's not error */
1004 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
1006 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
1010 * If the window size is greater than 1, then calculate
1011 * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
1012 * powers could instead be computed as (a^(i/2))^2 to use the slight
1013 * performance advantage of sqr over mul).
1016 if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
1018 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
1021 for (i = 3; i < numPowers; i++) {
1022 /* Calculate a^i = a^(i-1) * a */
1023 if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
1025 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
1032 for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
1033 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1034 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
1039 * Scan the exponent one window at a time starting from the most
1043 wvalue = 0; /* The 'value' of the window */
1045 /* Scan the window, squaring the result as we go */
1046 for (i = 0; i < window; i++, bits--) {
1047 if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
1049 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1053 * Fetch the appropriate pre-computed value from the pre-buf
1055 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
1059 /* Multiply the result into the intermediate result */
1060 if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
1065 /* Convert the final result from montgomery to standard format */
1066 #if defined(SPARC_T4_MONT)
1067 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
1068 am.d[0] = 1; /* borrow am */
1069 for (i = 1; i < top; i++)
1071 if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
1075 if (!BN_from_montgomery(rr, &tmp, mont, ctx))
1079 if (in_mont == NULL)
1080 BN_MONT_CTX_free(mont);
1081 if (powerbuf != NULL) {
1082 OPENSSL_cleanse(powerbuf, powerbufLen);
1083 OPENSSL_free(powerbufFree);
1089 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1090 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1092 BN_MONT_CTX *mont = NULL;
1093 int b, bits, ret = 0;
1098 #define BN_MOD_MUL_WORD(r, w, m) \
1099 (BN_mul_word(r, (w)) && \
1100 (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
1101 (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
1103 * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
1104 * probably more overhead than always using BN_mod (which uses BN_copy if
1105 * a similar test returns true).
1108 * We can use BN_mod and do not need BN_nnmod because our accumulator is
1109 * never negative (the result of BN_mod does not depend on the sign of
1112 #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
1113 (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
1115 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
1116 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1117 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1124 if (!BN_is_odd(m)) {
1125 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
1129 a %= m->d[0]; /* make sure that 'a' is reduced */
1131 bits = BN_num_bits(p);
1133 /* x**0 mod 1 is still zero. */
1149 d = BN_CTX_get(ctx);
1150 r = BN_CTX_get(ctx);
1151 t = BN_CTX_get(ctx);
1152 if (d == NULL || r == NULL || t == NULL)
1155 if (in_mont != NULL)
1158 if ((mont = BN_MONT_CTX_new()) == NULL)
1160 if (!BN_MONT_CTX_set(mont, m, ctx))
1164 r_is_one = 1; /* except for Montgomery factor */
1168 /* The result is accumulated in the product r*w. */
1169 w = a; /* bit 'bits-1' of 'p' is always set */
1170 for (b = bits - 2; b >= 0; b--) {
1171 /* First, square r*w. */
1173 if ((next_w / w) != w) { /* overflow */
1175 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1179 if (!BN_MOD_MUL_WORD(r, w, m))
1186 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
1190 /* Second, multiply r*w by 'a' if exponent bit is set. */
1191 if (BN_is_bit_set(p, b)) {
1193 if ((next_w / a) != w) { /* overflow */
1195 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1199 if (!BN_MOD_MUL_WORD(r, w, m))
1208 /* Finally, set r:=r*w. */
1211 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1215 if (!BN_MOD_MUL_WORD(r, w, m))
1220 if (r_is_one) { /* can happen only if a == 1 */
1224 if (!BN_from_montgomery(rr, r, mont, ctx))
1229 if (in_mont == NULL)
1230 BN_MONT_CTX_free(mont);
1236 /* The old fallback, simple version :-) */
1237 int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1238 const BIGNUM *m, BN_CTX *ctx)
1240 int i, j, bits, ret = 0, wstart, wend, window, wvalue;
1243 /* Table of variables obtained from 'ctx' */
1244 BIGNUM *val[TABLE_SIZE];
1246 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
1247 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1248 BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1252 bits = BN_num_bits(p);
1254 /* x**0 mod 1 is still zero. */
1265 d = BN_CTX_get(ctx);
1266 val[0] = BN_CTX_get(ctx);
1270 if (!BN_nnmod(val[0], a, m, ctx))
1272 if (BN_is_zero(val[0])) {
1278 window = BN_window_bits_for_exponent_size(bits);
1280 if (!BN_mod_mul(d, val[0], val[0], m, ctx))
1282 j = 1 << (window - 1);
1283 for (i = 1; i < j; i++) {
1284 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
1285 !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
1290 start = 1; /* This is used to avoid multiplication etc
1291 * when there is only the value '1' in the
1293 wvalue = 0; /* The 'value' of the window */
1294 wstart = bits - 1; /* The top bit of the window */
1295 wend = 0; /* The bottom bit of the window */
1301 if (BN_is_bit_set(p, wstart) == 0) {
1303 if (!BN_mod_mul(r, r, r, m, ctx))
1311 * We now have wstart on a 'set' bit, we now need to work out how bit
1312 * a window to do. To do this we need to scan forward until the last
1313 * set bit before the end of the window
1318 for (i = 1; i < window; i++) {
1321 if (BN_is_bit_set(p, wstart - i)) {
1322 wvalue <<= (i - wend);
1328 /* wend is the size of the current window */
1330 /* add the 'bytes above' */
1332 for (i = 0; i < j; i++) {
1333 if (!BN_mod_mul(r, r, r, m, ctx))
1337 /* wvalue will be an odd number < 2^window */
1338 if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
1341 /* move the 'window' down further */