ModularFunctions.cpp 12 KB

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