ModularFunctions.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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/BigInt/Algorithms/UnsignedBigIntegerAlgorithms.h>
  8. #include <LibCrypto/NumberTheory/ModularFunctions.h>
  9. namespace Crypto {
  10. namespace NumberTheory {
  11. UnsignedBigInteger ModularInverse(const UnsignedBigInteger& a_, const UnsignedBigInteger& b)
  12. {
  13. if (b == 1)
  14. return { 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_d;
  23. UnsignedBigInteger temp_u;
  24. UnsignedBigInteger temp_v;
  25. UnsignedBigInteger temp_x;
  26. UnsignedBigInteger result;
  27. UnsignedBigIntegerAlgorithms::modular_inverse_without_allocation(a_, b, temp_1, temp_2, temp_3, temp_4, temp_plus, temp_minus, temp_quotient, temp_d, temp_u, temp_v, temp_x, result);
  28. return result;
  29. }
  30. UnsignedBigInteger ModularPower(const UnsignedBigInteger& b, const UnsignedBigInteger& e, const UnsignedBigInteger& m)
  31. {
  32. if (m == 1)
  33. return 0;
  34. UnsignedBigInteger ep { e };
  35. UnsignedBigInteger base { b };
  36. UnsignedBigInteger result;
  37. UnsignedBigInteger temp_1;
  38. UnsignedBigInteger temp_2;
  39. UnsignedBigInteger temp_3;
  40. UnsignedBigInteger temp_4;
  41. UnsignedBigInteger temp_multiply;
  42. UnsignedBigInteger temp_quotient;
  43. UnsignedBigInteger temp_remainder;
  44. UnsignedBigIntegerAlgorithms::destructive_modular_power_without_allocation(ep, base, m, temp_1, temp_2, temp_3, temp_4, temp_multiply, temp_quotient, temp_remainder, result);
  45. return result;
  46. }
  47. UnsignedBigInteger GCD(const UnsignedBigInteger& a, const UnsignedBigInteger& b)
  48. {
  49. UnsignedBigInteger temp_a { a };
  50. UnsignedBigInteger temp_b { b };
  51. UnsignedBigInteger temp_1;
  52. UnsignedBigInteger temp_2;
  53. UnsignedBigInteger temp_3;
  54. UnsignedBigInteger temp_4;
  55. UnsignedBigInteger temp_quotient;
  56. UnsignedBigInteger temp_remainder;
  57. UnsignedBigInteger output;
  58. UnsignedBigIntegerAlgorithms::destructive_GCD_without_allocation(temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder, output);
  59. return output;
  60. }
  61. UnsignedBigInteger LCM(const UnsignedBigInteger& a, const UnsignedBigInteger& b)
  62. {
  63. UnsignedBigInteger temp_a { a };
  64. UnsignedBigInteger temp_b { b };
  65. UnsignedBigInteger temp_1;
  66. UnsignedBigInteger temp_2;
  67. UnsignedBigInteger temp_3;
  68. UnsignedBigInteger temp_4;
  69. UnsignedBigInteger temp_quotient;
  70. UnsignedBigInteger temp_remainder;
  71. UnsignedBigInteger gcd_output;
  72. UnsignedBigInteger output { 0 };
  73. UnsignedBigIntegerAlgorithms::destructive_GCD_without_allocation(temp_a, temp_b, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder, gcd_output);
  74. if (gcd_output == 0) {
  75. dbgln_if(NT_DEBUG, "GCD is zero");
  76. return output;
  77. }
  78. // output = (a / gcd_output) * b
  79. UnsignedBigIntegerAlgorithms::divide_without_allocation(a, gcd_output, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  80. UnsignedBigIntegerAlgorithms::multiply_without_allocation(temp_quotient, b, temp_1, temp_2, temp_3, temp_4, output);
  81. dbgln_if(NT_DEBUG, "quot: {} rem: {} out: {}", temp_quotient, temp_remainder, output);
  82. return output;
  83. }
  84. static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests)
  85. {
  86. // Written using Wikipedia:
  87. // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test
  88. VERIFY(!(n < 4));
  89. auto predecessor = n.minus({ 1 });
  90. auto d = predecessor;
  91. size_t r = 0;
  92. {
  93. auto div_result = d.divided_by(2);
  94. while (div_result.remainder == 0) {
  95. d = div_result.quotient;
  96. div_result = d.divided_by(2);
  97. ++r;
  98. }
  99. }
  100. if (r == 0) {
  101. // n - 1 is odd, so n was even. But there is only one even prime:
  102. return n == 2;
  103. }
  104. for (auto& a : tests) {
  105. // Technically: VERIFY(2 <= a && a <= n - 2)
  106. VERIFY(a < n);
  107. auto x = ModularPower(a, d, n);
  108. if (x == 1 || x == predecessor)
  109. continue;
  110. bool skip_this_witness = false;
  111. // r − 1 iterations.
  112. for (size_t i = 0; i < r - 1; ++i) {
  113. x = ModularPower(x, 2, n);
  114. if (x == predecessor) {
  115. skip_this_witness = true;
  116. break;
  117. }
  118. }
  119. if (skip_this_witness)
  120. continue;
  121. return false; // "composite"
  122. }
  123. return true; // "probably prime"
  124. }
  125. UnsignedBigInteger random_number(const UnsignedBigInteger& min, const UnsignedBigInteger& max_excluded)
  126. {
  127. VERIFY(min < max_excluded);
  128. auto range = max_excluded.minus(min);
  129. UnsignedBigInteger base;
  130. auto size = range.trimmed_length() * sizeof(u32) + 2;
  131. // "+2" is intentional (see below).
  132. ByteBuffer buffer;
  133. buffer.grow(size);
  134. auto* buf = buffer.data();
  135. fill_with_random(buf, size);
  136. UnsignedBigInteger random { buf, size };
  137. // At this point, `random` is a large number, in the range [0, 256^size).
  138. // To get down to the actual range, we could just compute random % range.
  139. // This introduces "modulo bias". However, since we added 2 to `size`,
  140. // we know that the generated range is at least 65536 times as large as the
  141. // required range! This means that the modulo bias is only 0.0015%, if all
  142. // inputs are chosen adversarially. Let's hope this is good enough.
  143. auto divmod = random.divided_by(range);
  144. // The proper way to fix this is to restart if `divmod.quotient` is maximal.
  145. return divmod.remainder.plus(min);
  146. }
  147. bool is_probably_prime(const UnsignedBigInteger& p)
  148. {
  149. // Is it a small number?
  150. if (p < 49) {
  151. u32 p_value = p.words()[0];
  152. // Is it a very small prime?
  153. if (p_value == 2 || p_value == 3 || p_value == 5 || p_value == 7)
  154. return true;
  155. // Is it the multiple of a very small prime?
  156. if (p_value % 2 == 0 || p_value % 3 == 0 || p_value % 5 == 0 || p_value % 7 == 0)
  157. return false;
  158. // Then it must be a prime, but not a very small prime, like 37.
  159. return true;
  160. }
  161. Vector<UnsignedBigInteger, 256> tests;
  162. // Make some good initial guesses that are guaranteed to find all primes < 2^64.
  163. tests.append(UnsignedBigInteger(2));
  164. tests.append(UnsignedBigInteger(3));
  165. tests.append(UnsignedBigInteger(5));
  166. tests.append(UnsignedBigInteger(7));
  167. tests.append(UnsignedBigInteger(11));
  168. tests.append(UnsignedBigInteger(13));
  169. UnsignedBigInteger seventeen { 17 };
  170. for (size_t i = tests.size(); i < 256; ++i) {
  171. tests.append(random_number(seventeen, p.minus(2)));
  172. }
  173. // Miller-Rabin's "error" is 8^-k. In adversarial cases, it's 4^-k.
  174. // With 200 random numbers, this would mean an error of about 2^-400.
  175. // So we don't need to worry too much about the quality of the random numbers.
  176. return MR_primality_test(p, tests);
  177. }
  178. UnsignedBigInteger random_big_prime(size_t bits)
  179. {
  180. VERIFY(bits >= 33);
  181. UnsignedBigInteger min = UnsignedBigInteger::from_base10("6074001000").shift_left(bits - 33);
  182. UnsignedBigInteger max = UnsignedBigInteger { 1 }.shift_left(bits).minus(1);
  183. for (;;) {
  184. auto p = random_number(min, max);
  185. if ((p.words()[0] & 1) == 0) {
  186. // An even number is definitely not a large prime.
  187. continue;
  188. }
  189. if (is_probably_prime(p))
  190. return p;
  191. }
  192. }
  193. }
  194. }