您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

208 行
7.5 KiB

  1. /* Copyright 2016 Brian Smith.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <openssl/bn.h>
  15. #include <assert.h>
  16. #include "internal.h"
  17. #include "../internal.h"
  18. static uint64_t bn_neg_inv_mod_r_u64(uint64_t n);
  19. OPENSSL_COMPILE_ASSERT(BN_MONT_CTX_N0_LIMBS == 1 || BN_MONT_CTX_N0_LIMBS == 2,
  20. BN_MONT_CTX_N0_LIMBS_VALUE_INVALID);
  21. OPENSSL_COMPILE_ASSERT(sizeof(uint64_t) ==
  22. BN_MONT_CTX_N0_LIMBS * sizeof(BN_ULONG),
  23. BN_MONT_CTX_N0_LIMBS_DOES_NOT_MATCH_UINT64_T);
  24. /* LG_LITTLE_R is log_2(r). */
  25. #define LG_LITTLE_R (BN_MONT_CTX_N0_LIMBS * BN_BITS2)
  26. uint64_t bn_mont_n0(const BIGNUM *n) {
  27. /* These conditions are checked by the caller, |BN_MONT_CTX_set|. */
  28. assert(!BN_is_zero(n));
  29. assert(!BN_is_negative(n));
  30. assert(BN_is_odd(n));
  31. /* r == 2**(BN_MONT_CTX_N0_LIMBS * BN_BITS2) and LG_LITTLE_R == lg(r). This
  32. * ensures that we can do integer division by |r| by simply ignoring
  33. * |BN_MONT_CTX_N0_LIMBS| limbs. Similarly, we can calculate values modulo
  34. * |r| by just looking at the lowest |BN_MONT_CTX_N0_LIMBS| limbs. This is
  35. * what makes Montgomery multiplication efficient.
  36. *
  37. * As shown in Algorithm 1 of "Fast Prime Field Elliptic Curve Cryptography
  38. * with 256 Bit Primes" by Shay Gueron and Vlad Krasnov, in the loop of a
  39. * multi-limb Montgomery multiplication of |a * b (mod n)|, given the
  40. * unreduced product |t == a * b|, we repeatedly calculate:
  41. *
  42. * t1 := t % r |t1| is |t|'s lowest limb (see previous paragraph).
  43. * t2 := t1*n0*n
  44. * t3 := t + t2
  45. * t := t3 / r copy all limbs of |t3| except the lowest to |t|.
  46. *
  47. * In the last step, it would only make sense to ignore the lowest limb of
  48. * |t3| if it were zero. The middle steps ensure that this is the case:
  49. *
  50. * t3 == 0 (mod r)
  51. * t + t2 == 0 (mod r)
  52. * t + t1*n0*n == 0 (mod r)
  53. * t1*n0*n == -t (mod r)
  54. * t*n0*n == -t (mod r)
  55. * n0*n == -1 (mod r)
  56. * n0 == -1/n (mod r)
  57. *
  58. * Thus, in each iteration of the loop, we multiply by the constant factor
  59. * |n0|, the negative inverse of n (mod r). */
  60. /* n_mod_r = n % r. As explained above, this is done by taking the lowest
  61. * |BN_MONT_CTX_N0_LIMBS| limbs of |n|. */
  62. uint64_t n_mod_r = n->d[0];
  63. #if BN_MONT_CTX_N0_LIMBS == 2
  64. if (n->top > 1) {
  65. n_mod_r |= (uint64_t)n->d[1] << BN_BITS2;
  66. }
  67. #endif
  68. return bn_neg_inv_mod_r_u64(n_mod_r);
  69. }
  70. /* bn_neg_inv_r_mod_n_u64 calculates the -1/n mod r; i.e. it calculates |v|
  71. * such that u*r - v*n == 1. |r| is the constant defined in |bn_mont_n0|. |n|
  72. * must be odd.
  73. *
  74. * This is derived from |xbinGCD| in Henry S. Warren, Jr.'s "Montgomery
  75. * Multiplication" (http://www.hackersdelight.org/MontgomeryMultiplication.pdf).
  76. * It is very similar to the MODULAR-INVERSE function in Stephen R. Dussé's and
  77. * Burton S. Kaliski Jr.'s "A Cryptographic Library for the Motorola DSP56000"
  78. * (http://link.springer.com/chapter/10.1007%2F3-540-46877-3_21).
  79. *
  80. * This is inspired by Joppe W. Bos's "Constant Time Modular Inversion"
  81. * (http://www.joppebos.com/files/CTInversion.pdf) so that the inversion is
  82. * constant-time with respect to |n|. We assume uint64_t additions,
  83. * subtractions, shifts, and bitwise operations are all constant time, which
  84. * may be a large leap of faith on 32-bit targets. We avoid division and
  85. * multiplication, which tend to be the most problematic in terms of timing
  86. * leaks.
  87. *
  88. * Most GCD implementations return values such that |u*r + v*n == 1|, so the
  89. * caller would have to negate the resultant |v| for the purpose of Montgomery
  90. * multiplication. This implementation does the negation implicitly by doing
  91. * the computations as a difference instead of a sum. */
  92. static uint64_t bn_neg_inv_mod_r_u64(uint64_t n) {
  93. assert(n % 2 == 1);
  94. /* alpha == 2**(lg r - 1) == r / 2. */
  95. static const uint64_t alpha = UINT64_C(1) << (LG_LITTLE_R - 1);
  96. const uint64_t beta = n;
  97. uint64_t u = 1;
  98. uint64_t v = 0;
  99. /* The invariant maintained from here on is:
  100. * 2**(lg r - i) == u*2*alpha - v*beta. */
  101. for (size_t i = 0; i < LG_LITTLE_R; ++i) {
  102. #if BN_BITS2 == 64 && defined(BN_ULLONG)
  103. assert((BN_ULLONG)(1) << (LG_LITTLE_R - i) ==
  104. ((BN_ULLONG)u * 2 * alpha) - ((BN_ULLONG)v * beta));
  105. #endif
  106. /* Delete a common factor of 2 in u and v if |u| is even. Otherwise, set
  107. * |u = (u + beta) / 2| and |v = (v / 2) + alpha|. */
  108. uint64_t u_is_odd = UINT64_C(0) - (u & 1); /* Either 0xff..ff or 0. */
  109. /* The addition can overflow, so use Dietz's method for it.
  110. *
  111. * Dietz calculates (x+y)/2 by (x⊕y)>>1 + x&y. This is valid for all
  112. * (unsigned) x and y, even when x+y overflows. Evidence for 32-bit values
  113. * (embedded in 64 bits to so that overflow can be ignored):
  114. *
  115. * (declare-fun x () (_ BitVec 64))
  116. * (declare-fun y () (_ BitVec 64))
  117. * (assert (let (
  118. * (one (_ bv1 64))
  119. * (thirtyTwo (_ bv32 64)))
  120. * (and
  121. * (bvult x (bvshl one thirtyTwo))
  122. * (bvult y (bvshl one thirtyTwo))
  123. * (not (=
  124. * (bvadd (bvlshr (bvxor x y) one) (bvand x y))
  125. * (bvlshr (bvadd x y) one)))
  126. * )))
  127. * (check-sat) */
  128. uint64_t beta_if_u_is_odd = beta & u_is_odd; /* Either |beta| or 0. */
  129. u = ((u ^ beta_if_u_is_odd) >> 1) + (u & beta_if_u_is_odd);
  130. uint64_t alpha_if_u_is_odd = alpha & u_is_odd; /* Either |alpha| or 0. */
  131. v = (v >> 1) + alpha_if_u_is_odd;
  132. }
  133. /* The invariant now shows that u*r - v*n == 1 since r == 2 * alpha. */
  134. #if BN_BITS2 == 64 && defined(BN_ULLONG)
  135. assert(1 == ((BN_ULLONG)u * 2 * alpha) - ((BN_ULLONG)v * beta));
  136. #endif
  137. return v;
  138. }
  139. /* bn_mod_exp_base_2_vartime calculates r = 2**p (mod n). |p| must be larger
  140. * than log_2(n); i.e. 2**p must be larger than |n|. |n| must be positive and
  141. * odd. */
  142. int bn_mod_exp_base_2_vartime(BIGNUM *r, unsigned p, const BIGNUM *n) {
  143. assert(!BN_is_zero(n));
  144. assert(!BN_is_negative(n));
  145. assert(BN_is_odd(n));
  146. BN_zero(r);
  147. unsigned n_bits = BN_num_bits(n);
  148. assert(n_bits != 0);
  149. if (n_bits == 1) {
  150. return 1;
  151. }
  152. /* Set |r| to the smallest power of two larger than |n|. */
  153. assert(p > n_bits);
  154. if (!BN_set_bit(r, n_bits)) {
  155. return 0;
  156. }
  157. /* Unconditionally reduce |r|. */
  158. assert(BN_cmp(r, n) > 0);
  159. if (!BN_usub(r, r, n)) {
  160. return 0;
  161. }
  162. assert(BN_cmp(r, n) < 0);
  163. for (unsigned i = n_bits; i < p; ++i) {
  164. /* This is like |BN_mod_lshift1_quick| except using |BN_usub|.
  165. *
  166. * TODO: Replace this with the use of a constant-time variant of
  167. * |BN_mod_lshift1_quick|. */
  168. if (!BN_lshift1(r, r)) {
  169. return 0;
  170. }
  171. if (BN_cmp(r, n) >= 0) {
  172. if (!BN_usub(r, r, n)) {
  173. return 0;
  174. }
  175. }
  176. }
  177. return 1;
  178. }