ModularFunctions.cpp 11 KB

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