ModularFunctions.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. #if NT_DEBUG
  179. dbgln("GCD is zero");
  180. #endif
  181. return output;
  182. }
  183. // output = (a / gcd_output) * b
  184. UnsignedBigInteger::divide_without_allocation(a, gcd_output, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  185. UnsignedBigInteger::multiply_without_allocation(temp_quotient, b, temp_1, temp_2, temp_3, temp_4, output);
  186. dbgln_if(NT_DEBUG, "quot: {} rem: {} out: {}", temp_quotient, temp_remainder, output);
  187. return output;
  188. }
  189. static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests)
  190. {
  191. // Written using Wikipedia:
  192. // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test
  193. VERIFY(!(n < 4));
  194. auto predecessor = n.minus({ 1 });
  195. auto d = predecessor;
  196. size_t r = 0;
  197. {
  198. auto div_result = d.divided_by(2);
  199. while (div_result.remainder == 0) {
  200. d = div_result.quotient;
  201. div_result = d.divided_by(2);
  202. ++r;
  203. }
  204. }
  205. if (r == 0) {
  206. // n - 1 is odd, so n was even. But there is only one even prime:
  207. return n == 2;
  208. }
  209. for (auto& a : tests) {
  210. // Technically: VERIFY(2 <= a && a <= n - 2)
  211. VERIFY(a < n);
  212. auto x = ModularPower(a, d, n);
  213. if (x == 1 || x == predecessor)
  214. continue;
  215. bool skip_this_witness = false;
  216. // r − 1 iterations.
  217. for (size_t i = 0; i < r - 1; ++i) {
  218. x = ModularPower(x, 2, n);
  219. if (x == predecessor) {
  220. skip_this_witness = true;
  221. break;
  222. }
  223. }
  224. if (skip_this_witness)
  225. continue;
  226. return false; // "composite"
  227. }
  228. return true; // "probably prime"
  229. }
  230. UnsignedBigInteger random_number(const UnsignedBigInteger& min, const UnsignedBigInteger& max_excluded)
  231. {
  232. VERIFY(min < max_excluded);
  233. auto range = max_excluded.minus(min);
  234. UnsignedBigInteger base;
  235. auto size = range.trimmed_length() * sizeof(u32) + 2;
  236. // "+2" is intentional (see below).
  237. // Also, if we're about to crash anyway, at least produce a nice error:
  238. VERIFY(size < 8 * MiB);
  239. u8 buf[size];
  240. fill_with_random(buf, size);
  241. UnsignedBigInteger random { buf, size };
  242. // At this point, `random` is a large number, in the range [0, 256^size).
  243. // To get down to the actual range, we could just compute random % range.
  244. // This introduces "modulo bias". However, since we added 2 to `size`,
  245. // we know that the generated range is at least 65536 times as large as the
  246. // required range! This means that the modulo bias is only 0.0015%, if all
  247. // inputs are chosen adversarially. Let's hope this is good enough.
  248. auto divmod = random.divided_by(range);
  249. // The proper way to fix this is to restart if `divmod.quotient` is maximal.
  250. return divmod.remainder.plus(min);
  251. }
  252. bool is_probably_prime(const UnsignedBigInteger& p)
  253. {
  254. // Is it a small number?
  255. if (p < 49) {
  256. u32 p_value = p.words()[0];
  257. // Is it a very small prime?
  258. if (p_value == 2 || p_value == 3 || p_value == 5 || p_value == 7)
  259. return true;
  260. // Is it the multiple of a very small prime?
  261. if (p_value % 2 == 0 || p_value % 3 == 0 || p_value % 5 == 0 || p_value % 7 == 0)
  262. return false;
  263. // Then it must be a prime, but not a very small prime, like 37.
  264. return true;
  265. }
  266. Vector<UnsignedBigInteger, 256> tests;
  267. // Make some good initial guesses that are guaranteed to find all primes < 2^64.
  268. tests.append(UnsignedBigInteger(2));
  269. tests.append(UnsignedBigInteger(3));
  270. tests.append(UnsignedBigInteger(5));
  271. tests.append(UnsignedBigInteger(7));
  272. tests.append(UnsignedBigInteger(11));
  273. tests.append(UnsignedBigInteger(13));
  274. UnsignedBigInteger seventeen { 17 };
  275. for (size_t i = tests.size(); i < 256; ++i) {
  276. tests.append(random_number(seventeen, p.minus(2)));
  277. }
  278. // Miller-Rabin's "error" is 8^-k. In adversarial cases, it's 4^-k.
  279. // With 200 random numbers, this would mean an error of about 2^-400.
  280. // So we don't need to worry too much about the quality of the random numbers.
  281. return MR_primality_test(p, tests);
  282. }
  283. UnsignedBigInteger random_big_prime(size_t bits)
  284. {
  285. VERIFY(bits >= 33);
  286. UnsignedBigInteger min = UnsignedBigInteger::from_base10("6074001000").shift_left(bits - 33);
  287. UnsignedBigInteger max = UnsignedBigInteger { 1 }.shift_left(bits).minus(1);
  288. for (;;) {
  289. auto p = random_number(min, max);
  290. if ((p.words()[0] & 1) == 0) {
  291. // An even number is definitely not a large prime.
  292. continue;
  293. }
  294. if (is_probably_prime(p))
  295. return p;
  296. }
  297. }
  298. }
  299. }