ModularFunctions.h 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. #pragma once
  27. #include <LibCrypto/BigInt/UnsignedBigInteger.h>
  28. //#define NT_DEBUG
  29. namespace Crypto {
  30. namespace NumberTheory {
  31. static auto ModularInverse(const UnsignedBigInteger& a_, const UnsignedBigInteger& b) -> UnsignedBigInteger
  32. {
  33. if (b == 1)
  34. return { 1 };
  35. auto a = a_;
  36. auto u = a;
  37. if (a.words()[0] % 2 == 0)
  38. u = u.add(b);
  39. auto v = b;
  40. auto x = UnsignedBigInteger { 0 };
  41. auto d = b.sub(1);
  42. while (!(v == 1)) {
  43. while (v < u) {
  44. u = u.sub(v);
  45. d = d.add(x);
  46. while (u.words()[0] % 2 == 0) {
  47. if (d.words()[0] % 2 == 1) {
  48. d = d.add(b);
  49. }
  50. u = u.divide(2).quotient;
  51. d = d.divide(2).quotient;
  52. }
  53. }
  54. v = v.sub(u);
  55. x = x.add(d);
  56. while (v.words()[0] % 2 == 0) {
  57. if (x.words()[0] % 2 == 1) {
  58. x = x.add(b);
  59. }
  60. v = v.divide(2).quotient;
  61. x = x.divide(2).quotient;
  62. }
  63. }
  64. return x.divide(b).remainder;
  65. }
  66. static auto ModularPower(const UnsignedBigInteger& b, const UnsignedBigInteger& e, const UnsignedBigInteger& m) -> UnsignedBigInteger
  67. {
  68. if (m == 1)
  69. return 0;
  70. UnsignedBigInteger ep { e };
  71. UnsignedBigInteger base { b };
  72. UnsignedBigInteger exp { 1 };
  73. while (!(ep < 1)) {
  74. #ifdef NT_DEBUG
  75. dbg() << ep.to_base10();
  76. #endif
  77. if (ep.words()[0] % 2 == 1) {
  78. exp = exp.multiply(base).divide(m).remainder;
  79. }
  80. ep = ep.divide(2).quotient;
  81. base = base.multiply(base).divide(m).remainder;
  82. }
  83. return exp;
  84. }
  85. static auto GCD(const UnsignedBigInteger& a, const UnsignedBigInteger& b) -> UnsignedBigInteger
  86. {
  87. UnsignedBigInteger a_ { a }, b_ { b };
  88. for (;;) {
  89. if (a_ == 0)
  90. return b_;
  91. b_ = b_.divide(a_).remainder;
  92. if (b_ == 0)
  93. return a_;
  94. a_ = a_.divide(b_).remainder;
  95. }
  96. }
  97. static auto LCM(const UnsignedBigInteger& a, const UnsignedBigInteger& b) -> UnsignedBigInteger
  98. {
  99. auto temp = GCD(a, b);
  100. auto div = a.divide(temp);
  101. #ifdef NT_DEBUG
  102. dbg() << "quot: " << div.quotient << " rem: " << div.remainder;
  103. #endif
  104. return temp == 0 ? 0 : (a.divide(temp).quotient.multiply(b));
  105. }
  106. template <size_t test_count>
  107. static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, test_count>& tests)
  108. {
  109. auto prev = n.sub({ 1 });
  110. auto b = prev;
  111. auto r = 0;
  112. auto div_result = b.divide(2);
  113. while (div_result.quotient == 0) {
  114. div_result = b.divide(2);
  115. b = div_result.quotient;
  116. ++r;
  117. }
  118. for (size_t i = 0; i < tests.size(); ++i) {
  119. auto return_ = true;
  120. if (n < tests[i])
  121. continue;
  122. auto x = ModularPower(tests[i], b, n);
  123. if (x == 1 || x == prev)
  124. continue;
  125. for (auto d = r - 1; d != 0; --d) {
  126. x = ModularPower(x, 2, n);
  127. if (x == 1)
  128. return false;
  129. if (x == prev) {
  130. return_ = false;
  131. break;
  132. }
  133. }
  134. if (return_)
  135. return false;
  136. }
  137. return true;
  138. }
  139. static UnsignedBigInteger random_number(const UnsignedBigInteger& min, const UnsignedBigInteger& max)
  140. {
  141. ASSERT(min < max);
  142. auto range = max.minus(min);
  143. UnsignedBigInteger base;
  144. // FIXME: Need a cryptographically secure rng
  145. auto size = range.trimmed_length() * sizeof(u32);
  146. u8 buf[size];
  147. arc4random_buf(buf, size);
  148. Vector<u32> vec;
  149. for (size_t i = 0; i < size / sizeof(u32); ++i) {
  150. vec.append(*(u32*)buf + i);
  151. }
  152. UnsignedBigInteger offset { move(vec) };
  153. return offset.add(min);
  154. }
  155. static bool is_probably_prime(const UnsignedBigInteger& p)
  156. {
  157. if (p == 2 || p == 3 || p == 5)
  158. return true;
  159. if (p < 49)
  160. return true;
  161. Vector<UnsignedBigInteger, 256> tests;
  162. UnsignedBigInteger seven { 7 };
  163. for (size_t i = 0; i < tests.size(); ++i)
  164. tests.append(random_number(seven, p.sub(2)));
  165. return MR_primality_test(p, tests);
  166. }
  167. static UnsignedBigInteger random_big_prime(size_t bits)
  168. {
  169. ASSERT(bits >= 33);
  170. UnsignedBigInteger min = UnsignedBigInteger::from_base10("6074001000").shift_left(bits - 33);
  171. UnsignedBigInteger max = UnsignedBigInteger { 1 }.shift_left(bits).sub(1);
  172. for (;;) {
  173. auto p = random_number(min, max);
  174. if (is_probably_prime(p))
  175. return p;
  176. }
  177. }
  178. }
  179. }