gcd.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com). */
  108. #include <openssl/bn.h>
  109. #include <assert.h>
  110. #include <openssl/err.h>
  111. #include "internal.h"
  112. static BN_ULONG word_is_odd_mask(BN_ULONG a) { return (BN_ULONG)0 - (a & 1); }
  113. static void maybe_rshift1_words(BN_ULONG *a, BN_ULONG mask, BN_ULONG *tmp,
  114. size_t num) {
  115. bn_rshift1_words(tmp, a, num);
  116. bn_select_words(a, mask, tmp, a, num);
  117. }
  118. static void maybe_rshift1_words_carry(BN_ULONG *a, BN_ULONG carry,
  119. BN_ULONG mask, BN_ULONG *tmp,
  120. size_t num) {
  121. maybe_rshift1_words(a, mask, tmp, num);
  122. if (num != 0) {
  123. carry &= mask;
  124. a[num - 1] |= carry << (BN_BITS2-1);
  125. }
  126. }
  127. static BN_ULONG maybe_add_words(BN_ULONG *a, BN_ULONG mask, const BN_ULONG *b,
  128. BN_ULONG *tmp, size_t num) {
  129. BN_ULONG carry = bn_add_words(tmp, a, b, num);
  130. bn_select_words(a, mask, tmp, a, num);
  131. return carry & mask;
  132. }
  133. static int bn_gcd_consttime(BIGNUM *r, unsigned *out_shift, const BIGNUM *x,
  134. const BIGNUM *y, BN_CTX *ctx) {
  135. size_t width = x->width > y->width ? x->width : y->width;
  136. if (width == 0) {
  137. *out_shift = 0;
  138. BN_zero(r);
  139. return 1;
  140. }
  141. // This is a constant-time implementation of Stein's algorithm (binary GCD).
  142. int ret = 0;
  143. BN_CTX_start(ctx);
  144. BIGNUM *u = BN_CTX_get(ctx);
  145. BIGNUM *v = BN_CTX_get(ctx);
  146. BIGNUM *tmp = BN_CTX_get(ctx);
  147. if (u == NULL || v == NULL || tmp == NULL ||
  148. !BN_copy(u, x) ||
  149. !BN_copy(v, y) ||
  150. !bn_resize_words(u, width) ||
  151. !bn_resize_words(v, width) ||
  152. !bn_resize_words(tmp, width)) {
  153. goto err;
  154. }
  155. // Each loop iteration halves at least one of |u| and |v|. Thus we need at
  156. // most the combined bit width of inputs for at least one value to be zero.
  157. unsigned x_bits = x->width * BN_BITS2, y_bits = y->width * BN_BITS2;
  158. unsigned num_iters = x_bits + y_bits;
  159. if (num_iters < x_bits) {
  160. OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG);
  161. goto err;
  162. }
  163. unsigned shift = 0;
  164. for (unsigned i = 0; i < num_iters; i++) {
  165. BN_ULONG both_odd = word_is_odd_mask(u->d[0]) & word_is_odd_mask(v->d[0]);
  166. // If both |u| and |v| are odd, subtract the smaller from the larger.
  167. BN_ULONG u_less_than_v =
  168. (BN_ULONG)0 - bn_sub_words(tmp->d, u->d, v->d, width);
  169. bn_select_words(u->d, both_odd & ~u_less_than_v, tmp->d, u->d, width);
  170. bn_sub_words(tmp->d, v->d, u->d, width);
  171. bn_select_words(v->d, both_odd & u_less_than_v, tmp->d, v->d, width);
  172. // At least one of |u| and |v| is now even.
  173. BN_ULONG u_is_odd = word_is_odd_mask(u->d[0]);
  174. BN_ULONG v_is_odd = word_is_odd_mask(v->d[0]);
  175. assert(!(u_is_odd & v_is_odd));
  176. // If both are even, the final GCD gains a factor of two.
  177. shift += 1 & (~u_is_odd & ~v_is_odd);
  178. // Halve any which are even.
  179. maybe_rshift1_words(u->d, ~u_is_odd, tmp->d, width);
  180. maybe_rshift1_words(v->d, ~v_is_odd, tmp->d, width);
  181. }
  182. // One of |u| or |v| is zero at this point. The algorithm usually makes |u|
  183. // zero, unless |y| was already zero on input. Fix this by combining the
  184. // values.
  185. assert(BN_is_zero(u) || BN_is_zero(v));
  186. for (size_t i = 0; i < width; i++) {
  187. v->d[i] |= u->d[i];
  188. }
  189. *out_shift = shift;
  190. ret = bn_set_words(r, v->d, width);
  191. err:
  192. BN_CTX_end(ctx);
  193. return ret;
  194. }
  195. int BN_gcd(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx) {
  196. unsigned shift;
  197. return bn_gcd_consttime(r, &shift, x, y, ctx) &&
  198. BN_lshift(r, r, shift);
  199. }
  200. int bn_is_relatively_prime(int *out_relatively_prime, const BIGNUM *x,
  201. const BIGNUM *y, BN_CTX *ctx) {
  202. int ret = 0;
  203. BN_CTX_start(ctx);
  204. unsigned shift;
  205. BIGNUM *gcd = BN_CTX_get(ctx);
  206. if (gcd == NULL ||
  207. !bn_gcd_consttime(gcd, &shift, x, y, ctx)) {
  208. goto err;
  209. }
  210. // Check that 2^|shift| * |gcd| is one.
  211. if (gcd->width == 0) {
  212. *out_relatively_prime = 0;
  213. } else {
  214. BN_ULONG mask = shift | (gcd->d[0] ^ 1);
  215. for (int i = 1; i < gcd->width; i++) {
  216. mask |= gcd->d[i];
  217. }
  218. *out_relatively_prime = mask == 0;
  219. }
  220. ret = 1;
  221. err:
  222. BN_CTX_end(ctx);
  223. return ret;
  224. }
  225. int bn_lcm_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) {
  226. BN_CTX_start(ctx);
  227. unsigned shift;
  228. BIGNUM *gcd = BN_CTX_get(ctx);
  229. int ret = gcd != NULL &&
  230. bn_mul_consttime(r, a, b, ctx) &&
  231. bn_gcd_consttime(gcd, &shift, a, b, ctx) &&
  232. bn_div_consttime(r, NULL, r, gcd, ctx) &&
  233. bn_rshift_secret_shift(r, r, shift, ctx);
  234. BN_CTX_end(ctx);
  235. return ret;
  236. }
  237. int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a,
  238. const BIGNUM *n, BN_CTX *ctx) {
  239. *out_no_inverse = 0;
  240. if (BN_is_negative(a) || BN_ucmp(a, n) >= 0) {
  241. OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
  242. return 0;
  243. }
  244. if (BN_is_zero(a)) {
  245. if (BN_is_one(n)) {
  246. BN_zero(r);
  247. return 1;
  248. }
  249. *out_no_inverse = 1;
  250. OPENSSL_PUT_ERROR(BN, BN_R_NO_INVERSE);
  251. return 0;
  252. }
  253. // This is a constant-time implementation of the extended binary GCD
  254. // algorithm. It is adapted from the Handbook of Applied Cryptography, section
  255. // 14.4.3, algorithm 14.51, and modified to bound coefficients and avoid
  256. // negative numbers.
  257. //
  258. // For more details and proof of correctness, see
  259. // https://github.com/mit-plv/fiat-crypto/pull/333. In particular, see |step|
  260. // and |mod_inverse_consttime| for the algorithm in Gallina and see
  261. // |mod_inverse_consttime_spec| for the correctness result.
  262. if (!BN_is_odd(a) && !BN_is_odd(n)) {
  263. *out_no_inverse = 1;
  264. OPENSSL_PUT_ERROR(BN, BN_R_NO_INVERSE);
  265. return 0;
  266. }
  267. // This function exists to compute the RSA private exponent, where |a| is one
  268. // word. We'll thus use |a_width| when available.
  269. size_t n_width = n->width, a_width = a->width;
  270. if (a_width > n_width) {
  271. a_width = n_width;
  272. }
  273. int ret = 0;
  274. BN_CTX_start(ctx);
  275. BIGNUM *u = BN_CTX_get(ctx);
  276. BIGNUM *v = BN_CTX_get(ctx);
  277. BIGNUM *A = BN_CTX_get(ctx);
  278. BIGNUM *B = BN_CTX_get(ctx);
  279. BIGNUM *C = BN_CTX_get(ctx);
  280. BIGNUM *D = BN_CTX_get(ctx);
  281. BIGNUM *tmp = BN_CTX_get(ctx);
  282. BIGNUM *tmp2 = BN_CTX_get(ctx);
  283. if (u == NULL || v == NULL || A == NULL || B == NULL || C == NULL ||
  284. D == NULL || tmp == NULL || tmp2 == NULL ||
  285. !BN_copy(u, a) ||
  286. !BN_copy(v, n) ||
  287. !BN_one(A) ||
  288. !BN_one(D) ||
  289. // For convenience, size |u| and |v| equivalently.
  290. !bn_resize_words(u, n_width) ||
  291. !bn_resize_words(v, n_width) ||
  292. // |A| and |C| are bounded by |m|.
  293. !bn_resize_words(A, n_width) ||
  294. !bn_resize_words(C, n_width) ||
  295. // |B| and |D| are bounded by |a|.
  296. !bn_resize_words(B, a_width) ||
  297. !bn_resize_words(D, a_width) ||
  298. // |tmp| and |tmp2| may be used at either size.
  299. !bn_resize_words(tmp, n_width) ||
  300. !bn_resize_words(tmp2, n_width)) {
  301. goto err;
  302. }
  303. // Each loop iteration halves at least one of |u| and |v|. Thus we need at
  304. // most the combined bit width of inputs for at least one value to be zero.
  305. unsigned a_bits = a_width * BN_BITS2, n_bits = n_width * BN_BITS2;
  306. unsigned num_iters = a_bits + n_bits;
  307. if (num_iters < a_bits) {
  308. OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG);
  309. goto err;
  310. }
  311. // Before and after each loop iteration, the following hold:
  312. //
  313. // u = A*a - B*n
  314. // v = D*n - C*a
  315. // 0 < u <= a
  316. // 0 <= v <= n
  317. // 0 <= A < n
  318. // 0 <= B <= a
  319. // 0 <= C < n
  320. // 0 <= D <= a
  321. //
  322. // After each loop iteration, u and v only get smaller, and at least one of
  323. // them shrinks by at least a factor of two.
  324. for (unsigned i = 0; i < num_iters; i++) {
  325. BN_ULONG both_odd = word_is_odd_mask(u->d[0]) & word_is_odd_mask(v->d[0]);
  326. // If both |u| and |v| are odd, subtract the smaller from the larger.
  327. BN_ULONG v_less_than_u =
  328. (BN_ULONG)0 - bn_sub_words(tmp->d, v->d, u->d, n_width);
  329. bn_select_words(v->d, both_odd & ~v_less_than_u, tmp->d, v->d, n_width);
  330. bn_sub_words(tmp->d, u->d, v->d, n_width);
  331. bn_select_words(u->d, both_odd & v_less_than_u, tmp->d, u->d, n_width);
  332. // If we updated one of the values, update the corresponding coefficient.
  333. BN_ULONG carry = bn_add_words(tmp->d, A->d, C->d, n_width);
  334. carry -= bn_sub_words(tmp2->d, tmp->d, n->d, n_width);
  335. bn_select_words(tmp->d, carry, tmp->d, tmp2->d, n_width);
  336. bn_select_words(A->d, both_odd & v_less_than_u, tmp->d, A->d, n_width);
  337. bn_select_words(C->d, both_odd & ~v_less_than_u, tmp->d, C->d, n_width);
  338. bn_add_words(tmp->d, B->d, D->d, a_width);
  339. bn_sub_words(tmp2->d, tmp->d, a->d, a_width);
  340. bn_select_words(tmp->d, carry, tmp->d, tmp2->d, a_width);
  341. bn_select_words(B->d, both_odd & v_less_than_u, tmp->d, B->d, a_width);
  342. bn_select_words(D->d, both_odd & ~v_less_than_u, tmp->d, D->d, a_width);
  343. // Our loop invariants hold at this point. Additionally, exactly one of |u|
  344. // and |v| is now even.
  345. BN_ULONG u_is_even = ~word_is_odd_mask(u->d[0]);
  346. BN_ULONG v_is_even = ~word_is_odd_mask(v->d[0]);
  347. assert(u_is_even != v_is_even);
  348. // Halve the even one and adjust the corresponding coefficient.
  349. maybe_rshift1_words(u->d, u_is_even, tmp->d, n_width);
  350. BN_ULONG A_or_B_is_odd =
  351. word_is_odd_mask(A->d[0]) | word_is_odd_mask(B->d[0]);
  352. BN_ULONG A_carry =
  353. maybe_add_words(A->d, A_or_B_is_odd & u_is_even, n->d, tmp->d, n_width);
  354. BN_ULONG B_carry =
  355. maybe_add_words(B->d, A_or_B_is_odd & u_is_even, a->d, tmp->d, a_width);
  356. maybe_rshift1_words_carry(A->d, A_carry, u_is_even, tmp->d, n_width);
  357. maybe_rshift1_words_carry(B->d, B_carry, u_is_even, tmp->d, a_width);
  358. maybe_rshift1_words(v->d, v_is_even, tmp->d, n_width);
  359. BN_ULONG C_or_D_is_odd =
  360. word_is_odd_mask(C->d[0]) | word_is_odd_mask(D->d[0]);
  361. BN_ULONG C_carry =
  362. maybe_add_words(C->d, C_or_D_is_odd & v_is_even, n->d, tmp->d, n_width);
  363. BN_ULONG D_carry =
  364. maybe_add_words(D->d, C_or_D_is_odd & v_is_even, a->d, tmp->d, a_width);
  365. maybe_rshift1_words_carry(C->d, C_carry, v_is_even, tmp->d, n_width);
  366. maybe_rshift1_words_carry(D->d, D_carry, v_is_even, tmp->d, a_width);
  367. }
  368. assert(BN_is_zero(v));
  369. if (!BN_is_one(u)) {
  370. *out_no_inverse = 1;
  371. OPENSSL_PUT_ERROR(BN, BN_R_NO_INVERSE);
  372. goto err;
  373. }
  374. ret = BN_copy(r, A) != NULL;
  375. err:
  376. BN_CTX_end(ctx);
  377. return ret;
  378. }
  379. int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a,
  380. const BIGNUM *n, BN_CTX *ctx) {
  381. *out_no_inverse = 0;
  382. if (!BN_is_odd(n)) {
  383. OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
  384. return 0;
  385. }
  386. if (BN_is_negative(a) || BN_cmp(a, n) >= 0) {
  387. OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
  388. return 0;
  389. }
  390. BIGNUM *A, *B, *X, *Y;
  391. int ret = 0;
  392. int sign;
  393. BN_CTX_start(ctx);
  394. A = BN_CTX_get(ctx);
  395. B = BN_CTX_get(ctx);
  396. X = BN_CTX_get(ctx);
  397. Y = BN_CTX_get(ctx);
  398. if (Y == NULL) {
  399. goto err;
  400. }
  401. BIGNUM *R = out;
  402. BN_zero(Y);
  403. if (!BN_one(X) || BN_copy(B, a) == NULL || BN_copy(A, n) == NULL) {
  404. goto err;
  405. }
  406. A->neg = 0;
  407. sign = -1;
  408. // From B = a mod |n|, A = |n| it follows that
  409. //
  410. // 0 <= B < A,
  411. // -sign*X*a == B (mod |n|),
  412. // sign*Y*a == A (mod |n|).
  413. // Binary inversion algorithm; requires odd modulus. This is faster than the
  414. // general algorithm if the modulus is sufficiently small (about 400 .. 500
  415. // bits on 32-bit systems, but much more on 64-bit systems)
  416. int shift;
  417. while (!BN_is_zero(B)) {
  418. // 0 < B < |n|,
  419. // 0 < A <= |n|,
  420. // (1) -sign*X*a == B (mod |n|),
  421. // (2) sign*Y*a == A (mod |n|)
  422. // Now divide B by the maximum possible power of two in the integers,
  423. // and divide X by the same value mod |n|.
  424. // When we're done, (1) still holds.
  425. shift = 0;
  426. while (!BN_is_bit_set(B, shift)) {
  427. // note that 0 < B
  428. shift++;
  429. if (BN_is_odd(X)) {
  430. if (!BN_uadd(X, X, n)) {
  431. goto err;
  432. }
  433. }
  434. // now X is even, so we can easily divide it by two
  435. if (!BN_rshift1(X, X)) {
  436. goto err;
  437. }
  438. }
  439. if (shift > 0) {
  440. if (!BN_rshift(B, B, shift)) {
  441. goto err;
  442. }
  443. }
  444. // Same for A and Y. Afterwards, (2) still holds.
  445. shift = 0;
  446. while (!BN_is_bit_set(A, shift)) {
  447. // note that 0 < A
  448. shift++;
  449. if (BN_is_odd(Y)) {
  450. if (!BN_uadd(Y, Y, n)) {
  451. goto err;
  452. }
  453. }
  454. // now Y is even
  455. if (!BN_rshift1(Y, Y)) {
  456. goto err;
  457. }
  458. }
  459. if (shift > 0) {
  460. if (!BN_rshift(A, A, shift)) {
  461. goto err;
  462. }
  463. }
  464. // We still have (1) and (2).
  465. // Both A and B are odd.
  466. // The following computations ensure that
  467. //
  468. // 0 <= B < |n|,
  469. // 0 < A < |n|,
  470. // (1) -sign*X*a == B (mod |n|),
  471. // (2) sign*Y*a == A (mod |n|),
  472. //
  473. // and that either A or B is even in the next iteration.
  474. if (BN_ucmp(B, A) >= 0) {
  475. // -sign*(X + Y)*a == B - A (mod |n|)
  476. if (!BN_uadd(X, X, Y)) {
  477. goto err;
  478. }
  479. // NB: we could use BN_mod_add_quick(X, X, Y, n), but that
  480. // actually makes the algorithm slower
  481. if (!BN_usub(B, B, A)) {
  482. goto err;
  483. }
  484. } else {
  485. // sign*(X + Y)*a == A - B (mod |n|)
  486. if (!BN_uadd(Y, Y, X)) {
  487. goto err;
  488. }
  489. // as above, BN_mod_add_quick(Y, Y, X, n) would slow things down
  490. if (!BN_usub(A, A, B)) {
  491. goto err;
  492. }
  493. }
  494. }
  495. if (!BN_is_one(A)) {
  496. *out_no_inverse = 1;
  497. OPENSSL_PUT_ERROR(BN, BN_R_NO_INVERSE);
  498. goto err;
  499. }
  500. // The while loop (Euclid's algorithm) ends when
  501. // A == gcd(a,n);
  502. // we have
  503. // sign*Y*a == A (mod |n|),
  504. // where Y is non-negative.
  505. if (sign < 0) {
  506. if (!BN_sub(Y, n, Y)) {
  507. goto err;
  508. }
  509. }
  510. // Now Y*a == A (mod |n|).
  511. // Y*a == 1 (mod |n|)
  512. if (!Y->neg && BN_ucmp(Y, n) < 0) {
  513. if (!BN_copy(R, Y)) {
  514. goto err;
  515. }
  516. } else {
  517. if (!BN_nnmod(R, Y, n, ctx)) {
  518. goto err;
  519. }
  520. }
  521. ret = 1;
  522. err:
  523. BN_CTX_end(ctx);
  524. return ret;
  525. }
  526. BIGNUM *BN_mod_inverse(BIGNUM *out, const BIGNUM *a, const BIGNUM *n,
  527. BN_CTX *ctx) {
  528. BIGNUM *new_out = NULL;
  529. if (out == NULL) {
  530. new_out = BN_new();
  531. if (new_out == NULL) {
  532. OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
  533. return NULL;
  534. }
  535. out = new_out;
  536. }
  537. int ok = 0;
  538. BIGNUM *a_reduced = NULL;
  539. if (a->neg || BN_ucmp(a, n) >= 0) {
  540. a_reduced = BN_dup(a);
  541. if (a_reduced == NULL) {
  542. goto err;
  543. }
  544. if (!BN_nnmod(a_reduced, a_reduced, n, ctx)) {
  545. goto err;
  546. }
  547. a = a_reduced;
  548. }
  549. int no_inverse;
  550. if (!BN_is_odd(n)) {
  551. if (!bn_mod_inverse_consttime(out, &no_inverse, a, n, ctx)) {
  552. goto err;
  553. }
  554. } else if (!BN_mod_inverse_odd(out, &no_inverse, a, n, ctx)) {
  555. goto err;
  556. }
  557. ok = 1;
  558. err:
  559. if (!ok) {
  560. BN_free(new_out);
  561. out = NULL;
  562. }
  563. BN_free(a_reduced);
  564. return out;
  565. }
  566. int BN_mod_inverse_blinded(BIGNUM *out, int *out_no_inverse, const BIGNUM *a,
  567. const BN_MONT_CTX *mont, BN_CTX *ctx) {
  568. *out_no_inverse = 0;
  569. if (BN_is_negative(a) || BN_cmp(a, &mont->N) >= 0) {
  570. OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
  571. return 0;
  572. }
  573. int ret = 0;
  574. BIGNUM blinding_factor;
  575. BN_init(&blinding_factor);
  576. if (!BN_rand_range_ex(&blinding_factor, 1, &mont->N) ||
  577. !BN_mod_mul_montgomery(out, &blinding_factor, a, mont, ctx) ||
  578. !BN_mod_inverse_odd(out, out_no_inverse, out, &mont->N, ctx) ||
  579. !BN_mod_mul_montgomery(out, &blinding_factor, out, mont, ctx)) {
  580. OPENSSL_PUT_ERROR(BN, ERR_R_BN_LIB);
  581. goto err;
  582. }
  583. ret = 1;
  584. err:
  585. BN_free(&blinding_factor);
  586. return ret;
  587. }
  588. int bn_mod_inverse_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p,
  589. BN_CTX *ctx, const BN_MONT_CTX *mont_p) {
  590. BN_CTX_start(ctx);
  591. BIGNUM *p_minus_2 = BN_CTX_get(ctx);
  592. int ok = p_minus_2 != NULL &&
  593. BN_copy(p_minus_2, p) &&
  594. BN_sub_word(p_minus_2, 2) &&
  595. BN_mod_exp_mont(out, a, p_minus_2, p, ctx, mont_p);
  596. BN_CTX_end(ctx);
  597. return ok;
  598. }
  599. int bn_mod_inverse_secret_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p,
  600. BN_CTX *ctx, const BN_MONT_CTX *mont_p) {
  601. BN_CTX_start(ctx);
  602. BIGNUM *p_minus_2 = BN_CTX_get(ctx);
  603. int ok = p_minus_2 != NULL &&
  604. BN_copy(p_minus_2, p) &&
  605. BN_sub_word(p_minus_2, 2) &&
  606. BN_mod_exp_mont_consttime(out, a, p_minus_2, p, ctx, mont_p);
  607. BN_CTX_end(ctx);
  608. return ok;
  609. }