ModularFunctions.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. if (ep.words()[0] % 2 == 1) {
  116. // exp = (exp * base) % m;
  117. UnsignedBigInteger::multiply_without_allocation(exp, base, temp_1, temp_2, temp_3, temp_4, temp_multiply);
  118. UnsignedBigInteger::divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  119. exp.set_to(temp_remainder);
  120. }
  121. // ep = ep / 2;
  122. UnsignedBigInteger::divide_u16_without_allocation(ep, 2, temp_quotient, temp_remainder);
  123. ep.set_to(temp_quotient);
  124. // base = (base * base) % m;
  125. UnsignedBigInteger::multiply_without_allocation(base, base, temp_1, temp_2, temp_3, temp_4, temp_multiply);
  126. UnsignedBigInteger::divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  127. base.set_to(temp_remainder);
  128. }
  129. return exp;
  130. }
  131. static void GCD_without_allocation(
  132. const UnsignedBigInteger& a,
  133. const UnsignedBigInteger& b,
  134. UnsignedBigInteger& temp_a,
  135. UnsignedBigInteger& temp_b,
  136. UnsignedBigInteger& temp_1,
  137. UnsignedBigInteger& temp_2,
  138. UnsignedBigInteger& temp_3,
  139. UnsignedBigInteger& temp_4,
  140. UnsignedBigInteger& temp_quotient,
  141. UnsignedBigInteger& temp_remainder,
  142. UnsignedBigInteger& output)
  143. {
  144. temp_a.set_to(a);
  145. temp_b.set_to(b);
  146. for (;;) {
  147. if (temp_a == 0) {
  148. output.set_to(temp_b);
  149. return;
  150. }
  151. // temp_b %= temp_a
  152. UnsignedBigInteger::divide_without_allocation(temp_b, temp_a, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  153. temp_b.set_to(temp_remainder);
  154. if (temp_b == 0) {
  155. output.set_to(temp_a);
  156. return;
  157. }
  158. // temp_a %= temp_b
  159. UnsignedBigInteger::divide_without_allocation(temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  160. temp_a.set_to(temp_remainder);
  161. }
  162. }
  163. UnsignedBigInteger GCD(const UnsignedBigInteger& a, const UnsignedBigInteger& b)
  164. {
  165. UnsignedBigInteger temp_a;
  166. UnsignedBigInteger temp_b;
  167. UnsignedBigInteger temp_1;
  168. UnsignedBigInteger temp_2;
  169. UnsignedBigInteger temp_3;
  170. UnsignedBigInteger temp_4;
  171. UnsignedBigInteger temp_quotient;
  172. UnsignedBigInteger temp_remainder;
  173. UnsignedBigInteger output;
  174. GCD_without_allocation(a, b, temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder, output);
  175. return output;
  176. }
  177. UnsignedBigInteger LCM(const UnsignedBigInteger& a, const UnsignedBigInteger& b)
  178. {
  179. UnsignedBigInteger temp_a;
  180. UnsignedBigInteger temp_b;
  181. UnsignedBigInteger temp_1;
  182. UnsignedBigInteger temp_2;
  183. UnsignedBigInteger temp_3;
  184. UnsignedBigInteger temp_4;
  185. UnsignedBigInteger temp_quotient;
  186. UnsignedBigInteger temp_remainder;
  187. UnsignedBigInteger gcd_output;
  188. UnsignedBigInteger output { 0 };
  189. GCD_without_allocation(a, b, temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder, gcd_output);
  190. if (gcd_output == 0) {
  191. #ifdef NT_DEBUG
  192. dbg() << "GCD is zero";
  193. #endif
  194. return output;
  195. }
  196. // output = (a / gcd_output) * b
  197. UnsignedBigInteger::divide_without_allocation(a, gcd_output, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  198. UnsignedBigInteger::multiply_without_allocation(temp_quotient, b, temp_1, temp_2, temp_3, temp_4, output);
  199. #ifdef NT_DEBUG
  200. dbg() << "quot: " << temp_quotient << " rem: " << temp_remainder << " out: " << output;
  201. #endif
  202. return output;
  203. }
  204. static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests)
  205. {
  206. // Written using Wikipedia:
  207. // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test
  208. ASSERT(!(n < 4));
  209. auto predecessor = n.minus({ 1 });
  210. auto d = predecessor;
  211. size_t r = 0;
  212. {
  213. auto div_result = d.divided_by(2);
  214. while (div_result.remainder == 0) {
  215. d = div_result.quotient;
  216. div_result = d.divided_by(2);
  217. ++r;
  218. }
  219. }
  220. if (r == 0) {
  221. // n - 1 is odd, so n was even. But there is only one even prime:
  222. return n == 2;
  223. }
  224. for (auto a : tests) {
  225. // Technically: ASSERT(2 <= a && a <= n - 2)
  226. ASSERT(a < n);
  227. auto x = ModularPower(a, d, n);
  228. if (x == 1 || x == predecessor)
  229. continue;
  230. bool skip_this_witness = false;
  231. // r − 1 iterations.
  232. for (size_t i = 0; i < r - 1; ++i) {
  233. x = ModularPower(x, 2, n);
  234. if (x == predecessor) {
  235. skip_this_witness = true;
  236. break;
  237. }
  238. }
  239. if (skip_this_witness)
  240. continue;
  241. return false; // "composite"
  242. }
  243. return true; // "probably prime"
  244. }
  245. UnsignedBigInteger random_number(const UnsignedBigInteger& min, const UnsignedBigInteger& max_excluded)
  246. {
  247. ASSERT(min < max_excluded);
  248. auto range = max_excluded.minus(min);
  249. UnsignedBigInteger base;
  250. auto size = range.trimmed_length() * sizeof(u32) + 2;
  251. // "+2" is intentional (see below).
  252. // Also, if we're about to crash anyway, at least produce a nice error:
  253. ASSERT(size < 8 * MiB);
  254. u8 buf[size];
  255. AK::fill_with_random(buf, size);
  256. UnsignedBigInteger random { buf, size };
  257. // At this point, `random` is a large number, in the range [0, 256^size).
  258. // To get down to the actual range, we could just compute random % range.
  259. // This introduces "modulo bias". However, since we added 2 to `size`,
  260. // we know that the generated range is at least 65536 times as large as the
  261. // required range! This means that the modulo bias is only 0.0015%, if all
  262. // inputs are chosen adversarially. Let's hope this is good enough.
  263. auto divmod = random.divided_by(range);
  264. // The proper way to fix this is to restart if `divmod.quotient` is maximal.
  265. return divmod.remainder.plus(min);
  266. }
  267. bool is_probably_prime(const UnsignedBigInteger& p)
  268. {
  269. // Is it a small number?
  270. if (p < 49) {
  271. u32 p_value = p.words()[0];
  272. // Is it a very small prime?
  273. if (p_value == 2 || p_value == 3 || p_value == 5 || p_value == 7)
  274. return true;
  275. // Is it the multiple of a very small prime?
  276. if (p_value % 2 == 0 || p_value % 3 == 0 || p_value % 5 == 0 || p_value % 7 == 0)
  277. return false;
  278. // Then it must be a prime, but not a very small prime, like 37.
  279. return true;
  280. }
  281. Vector<UnsignedBigInteger, 256> tests;
  282. // Make some good initial guesses that are guaranteed to find all primes < 2^64.
  283. tests.append(UnsignedBigInteger(2));
  284. tests.append(UnsignedBigInteger(3));
  285. tests.append(UnsignedBigInteger(5));
  286. tests.append(UnsignedBigInteger(7));
  287. tests.append(UnsignedBigInteger(11));
  288. tests.append(UnsignedBigInteger(13));
  289. UnsignedBigInteger seventeen { 17 };
  290. for (size_t i = tests.size(); i < 256; ++i) {
  291. tests.append(random_number(seventeen, p.minus(2)));
  292. }
  293. // Miller-Rabin's "error" is 8^-k. In adversarial cases, it's 4^-k.
  294. // With 200 random numbers, this would mean an error of about 2^-400.
  295. // So we don't need to worry too much about the quality of the random numbers.
  296. return MR_primality_test(p, tests);
  297. }
  298. UnsignedBigInteger random_big_prime(size_t bits)
  299. {
  300. ASSERT(bits >= 33);
  301. UnsignedBigInteger min = UnsignedBigInteger::from_base10("6074001000").shift_left(bits - 33);
  302. UnsignedBigInteger max = UnsignedBigInteger { 1 }.shift_left(bits).minus(1);
  303. for (;;) {
  304. auto p = random_number(min, max);
  305. if ((p.words()[0] & 1) == 0) {
  306. // An even number is definitely not a large prime.
  307. continue;
  308. }
  309. if (is_probably_prime(p))
  310. return p;
  311. }
  312. }
  313. }
  314. }