ModularFunctions.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <LibCrypto/NumberTheory/ModularFunctions.h>
  27. namespace Crypto {
  28. namespace NumberTheory {
  29. UnsignedBigInteger ModularInverse(const UnsignedBigInteger& a_, const UnsignedBigInteger& b)
  30. {
  31. if (b == 1)
  32. return { 1 };
  33. UnsignedBigInteger one { 1 };
  34. UnsignedBigInteger temp_1;
  35. UnsignedBigInteger temp_2;
  36. UnsignedBigInteger temp_3;
  37. UnsignedBigInteger temp_4;
  38. UnsignedBigInteger temp_plus;
  39. UnsignedBigInteger temp_minus;
  40. UnsignedBigInteger temp_quotient;
  41. UnsignedBigInteger temp_remainder;
  42. UnsignedBigInteger d;
  43. auto a = a_;
  44. auto u = a;
  45. if (a.words()[0] % 2 == 0) {
  46. // u += b
  47. UnsignedBigInteger::add_without_allocation(u, b, temp_plus);
  48. u.set_to(temp_plus);
  49. }
  50. auto v = b;
  51. UnsignedBigInteger x { 0 };
  52. // d = b - 1
  53. UnsignedBigInteger::subtract_without_allocation(b, one, d);
  54. while (!(v == 1)) {
  55. while (v < u) {
  56. // u -= v
  57. UnsignedBigInteger::subtract_without_allocation(u, v, temp_minus);
  58. u.set_to(temp_minus);
  59. // d += x
  60. UnsignedBigInteger::add_without_allocation(d, x, temp_plus);
  61. d.set_to(temp_plus);
  62. while (u.words()[0] % 2 == 0) {
  63. if (d.words()[0] % 2 == 1) {
  64. // d += b
  65. UnsignedBigInteger::add_without_allocation(d, b, temp_plus);
  66. d.set_to(temp_plus);
  67. }
  68. // u /= 2
  69. UnsignedBigInteger::divide_u16_without_allocation(u, 2, temp_quotient, temp_remainder);
  70. u.set_to(temp_quotient);
  71. // d /= 2
  72. UnsignedBigInteger::divide_u16_without_allocation(d, 2, temp_quotient, temp_remainder);
  73. d.set_to(temp_quotient);
  74. }
  75. }
  76. // v -= u
  77. UnsignedBigInteger::subtract_without_allocation(v, u, temp_minus);
  78. v.set_to(temp_minus);
  79. // x += d
  80. UnsignedBigInteger::add_without_allocation(x, d, temp_plus);
  81. x.set_to(temp_plus);
  82. while (v.words()[0] % 2 == 0) {
  83. if (x.words()[0] % 2 == 1) {
  84. // x += b
  85. UnsignedBigInteger::add_without_allocation(x, b, temp_plus);
  86. x.set_to(temp_plus);
  87. }
  88. // v /= 2
  89. UnsignedBigInteger::divide_u16_without_allocation(v, 2, temp_quotient, temp_remainder);
  90. v.set_to(temp_quotient);
  91. // x /= 2
  92. UnsignedBigInteger::divide_u16_without_allocation(x, 2, temp_quotient, temp_remainder);
  93. x.set_to(temp_quotient);
  94. }
  95. }
  96. // x % b
  97. UnsignedBigInteger::divide_without_allocation(x, b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  98. return temp_remainder;
  99. }
  100. UnsignedBigInteger ModularPower(const UnsignedBigInteger& b, const UnsignedBigInteger& e, const UnsignedBigInteger& m)
  101. {
  102. if (m == 1)
  103. return 0;
  104. UnsignedBigInteger ep { e };
  105. UnsignedBigInteger base { b };
  106. UnsignedBigInteger exp { 1 };
  107. UnsignedBigInteger temp_1;
  108. UnsignedBigInteger temp_2;
  109. UnsignedBigInteger temp_3;
  110. UnsignedBigInteger temp_4;
  111. UnsignedBigInteger temp_multiply;
  112. UnsignedBigInteger temp_quotient;
  113. UnsignedBigInteger temp_remainder;
  114. while (!(ep < 1)) {
  115. #ifdef NT_DEBUG
  116. dbg() << ep.to_base10();
  117. #endif
  118. if (ep.words()[0] % 2 == 1) {
  119. // exp = (exp * base) % m;
  120. UnsignedBigInteger::multiply_without_allocation(exp, base, temp_1, temp_2, temp_3, temp_4, temp_multiply);
  121. UnsignedBigInteger::divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  122. exp.set_to(temp_remainder);
  123. }
  124. // ep = ep / 2;
  125. UnsignedBigInteger::divide_u16_without_allocation(ep, 2, temp_quotient, temp_remainder);
  126. ep.set_to(temp_quotient);
  127. // base = (base * base) % m;
  128. UnsignedBigInteger::multiply_without_allocation(base, base, temp_1, temp_2, temp_3, temp_4, temp_multiply);
  129. UnsignedBigInteger::divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  130. base.set_to(temp_remainder);
  131. }
  132. return exp;
  133. }
  134. static void GCD_without_allocation(
  135. const UnsignedBigInteger& a,
  136. const UnsignedBigInteger& b,
  137. UnsignedBigInteger& temp_a,
  138. UnsignedBigInteger& temp_b,
  139. UnsignedBigInteger& temp_1,
  140. UnsignedBigInteger& temp_2,
  141. UnsignedBigInteger& temp_3,
  142. UnsignedBigInteger& temp_4,
  143. UnsignedBigInteger& temp_quotient,
  144. UnsignedBigInteger& temp_remainder,
  145. UnsignedBigInteger& output)
  146. {
  147. temp_a.set_to(a);
  148. temp_b.set_to(b);
  149. for (;;) {
  150. if (temp_a == 0) {
  151. output.set_to(temp_b);
  152. return;
  153. }
  154. // temp_b %= temp_a
  155. UnsignedBigInteger::divide_without_allocation(temp_b, temp_a, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  156. temp_b.set_to(temp_remainder);
  157. if (temp_b == 0) {
  158. output.set_to(temp_a);
  159. return;
  160. }
  161. // temp_a %= temp_b
  162. UnsignedBigInteger::divide_without_allocation(temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  163. temp_a.set_to(temp_remainder);
  164. }
  165. }
  166. UnsignedBigInteger GCD(const UnsignedBigInteger& a, const UnsignedBigInteger& b)
  167. {
  168. UnsignedBigInteger temp_a;
  169. UnsignedBigInteger temp_b;
  170. UnsignedBigInteger temp_1;
  171. UnsignedBigInteger temp_2;
  172. UnsignedBigInteger temp_3;
  173. UnsignedBigInteger temp_4;
  174. UnsignedBigInteger temp_quotient;
  175. UnsignedBigInteger temp_remainder;
  176. UnsignedBigInteger output;
  177. GCD_without_allocation(a, b, temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder, output);
  178. return output;
  179. }
  180. UnsignedBigInteger LCM(const UnsignedBigInteger& a, const UnsignedBigInteger& b)
  181. {
  182. UnsignedBigInteger temp_a;
  183. UnsignedBigInteger temp_b;
  184. UnsignedBigInteger temp_1;
  185. UnsignedBigInteger temp_2;
  186. UnsignedBigInteger temp_3;
  187. UnsignedBigInteger temp_4;
  188. UnsignedBigInteger temp_quotient;
  189. UnsignedBigInteger temp_remainder;
  190. UnsignedBigInteger gcd_output;
  191. UnsignedBigInteger output { 0 };
  192. GCD_without_allocation(a, b, temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder, gcd_output);
  193. if (gcd_output == 0) {
  194. #ifdef NT_DEBUG
  195. dbg() << "GCD is zero";
  196. #endif
  197. return output;
  198. }
  199. // output = (a / gcd_output) * b
  200. UnsignedBigInteger::divide_without_allocation(a, gcd_output, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  201. UnsignedBigInteger::multiply_without_allocation(temp_quotient, b, temp_1, temp_2, temp_3, temp_4, output);
  202. #ifdef NT_DEBUG
  203. dbg() << "quot: " << temp_quotient << " rem: " << temp_remainder << " out: " << output;
  204. #endif
  205. return output;
  206. }
  207. static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests)
  208. {
  209. // Written using Wikipedia:
  210. // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test
  211. ASSERT(!(n < 4));
  212. auto predecessor = n.minus({ 1 });
  213. auto d = predecessor;
  214. size_t r = 0;
  215. {
  216. auto div_result = d.divided_by(2);
  217. while (div_result.remainder == 0) {
  218. d = div_result.quotient;
  219. div_result = d.divided_by(2);
  220. ++r;
  221. }
  222. }
  223. if (r == 0) {
  224. // n - 1 is odd, so n was even. But there is only one even prime:
  225. return n == 2;
  226. }
  227. for (auto a : tests) {
  228. // Technically: ASSERT(2 <= a && a <= n - 2)
  229. ASSERT(a < n);
  230. auto x = ModularPower(a, d, n);
  231. if (x == 1 || x == predecessor)
  232. continue;
  233. bool skip_this_witness = false;
  234. // r − 1 iterations.
  235. for (size_t i = 0; i < r - 1; ++i) {
  236. x = ModularPower(x, 2, n);
  237. if (x == predecessor) {
  238. skip_this_witness = true;
  239. break;
  240. }
  241. }
  242. if (skip_this_witness)
  243. continue;
  244. return false; // "composite"
  245. }
  246. return true; // "probably prime"
  247. }
  248. UnsignedBigInteger random_number(const UnsignedBigInteger& min, const UnsignedBigInteger& max_excluded)
  249. {
  250. ASSERT(min < max_excluded);
  251. auto range = max_excluded.minus(min);
  252. UnsignedBigInteger base;
  253. auto size = range.trimmed_length() * sizeof(u32) + 2;
  254. // "+2" is intentional (see below).
  255. // Also, if we're about to crash anyway, at least produce a nice error:
  256. ASSERT(size < 8 * MiB);
  257. u8 buf[size];
  258. AK::fill_with_random(buf, size);
  259. UnsignedBigInteger random { buf, size };
  260. // At this point, `random` is a large number, in the range [0, 256^size).
  261. // To get down to the actual range, we could just compute random % range.
  262. // This introduces "modulo bias". However, since we added 2 to `size`,
  263. // we know that the generated range is at least 65536 times as large as the
  264. // required range! This means that the modulo bias is only 0.0015%, if all
  265. // inputs are chosen adversarially. Let's hope this is good enough.
  266. auto divmod = random.divided_by(range);
  267. // The proper way to fix this is to restart if `divmod.quotient` is maximal.
  268. return divmod.remainder.plus(min);
  269. }
  270. bool is_probably_prime(const UnsignedBigInteger& p)
  271. {
  272. // Is it a small number?
  273. if (p < 49) {
  274. u32 p_value = p.words()[0];
  275. // Is it a very small prime?
  276. if (p_value == 2 || p_value == 3 || p_value == 5 || p_value == 7)
  277. return true;
  278. // Is it the multiple of a very small prime?
  279. if (p_value % 2 == 0 || p_value % 3 == 0 || p_value % 5 == 0 || p_value % 7 == 0)
  280. return false;
  281. // Then it must be a prime, but not a very small prime, like 37.
  282. return true;
  283. }
  284. Vector<UnsignedBigInteger, 256> tests;
  285. // Make some good initial guesses that are guaranteed to find all primes < 2^64.
  286. tests.append(UnsignedBigInteger(2));
  287. tests.append(UnsignedBigInteger(3));
  288. tests.append(UnsignedBigInteger(5));
  289. tests.append(UnsignedBigInteger(7));
  290. tests.append(UnsignedBigInteger(11));
  291. tests.append(UnsignedBigInteger(13));
  292. UnsignedBigInteger seventeen { 17 };
  293. for (size_t i = tests.size(); i < 256; ++i) {
  294. tests.append(random_number(seventeen, p.minus(2)));
  295. }
  296. // Miller-Rabin's "error" is 8^-k. In adversarial cases, it's 4^-k.
  297. // With 200 random numbers, this would mean an error of about 2^-400.
  298. // So we don't need to worry too much about the quality of the random numbers.
  299. return MR_primality_test(p, tests);
  300. }
  301. UnsignedBigInteger random_big_prime(size_t bits)
  302. {
  303. ASSERT(bits >= 33);
  304. UnsignedBigInteger min = UnsignedBigInteger::from_base10("6074001000").shift_left(bits - 33);
  305. UnsignedBigInteger max = UnsignedBigInteger { 1 }.shift_left(bits).minus(1);
  306. for (;;) {
  307. auto p = random_number(min, max);
  308. if ((p.words()[0] & 1) == 0) {
  309. // An even number is definitely not a large prime.
  310. continue;
  311. }
  312. if (is_probably_prime(p))
  313. return p;
  314. }
  315. }
  316. }
  317. }