ModularFunctions.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Random.h>
  8. #include <LibCrypto/BigInt/UnsignedBigInteger.h>
  9. namespace Crypto::NumberTheory {
  10. UnsignedBigInteger ModularInverse(UnsignedBigInteger const& a_, UnsignedBigInteger const& b);
  11. UnsignedBigInteger ModularPower(UnsignedBigInteger const& b, UnsignedBigInteger const& e, UnsignedBigInteger const& m);
  12. // Note: This function _will_ generate extremely huge numbers, and in doing so,
  13. // it will allocate and free a lot of memory!
  14. // Please use |ModularPower| if your use-case is modexp.
  15. template<typename IntegerType>
  16. static IntegerType Power(IntegerType const& b, IntegerType const& e)
  17. {
  18. IntegerType ep { e };
  19. IntegerType base { b };
  20. IntegerType exp { 1 };
  21. while (!(ep < IntegerType { 1 })) {
  22. if (ep.words()[0] % 2 == 1)
  23. exp.set_to(exp.multiplied_by(base));
  24. // ep = ep / 2;
  25. ep.set_to(ep.divided_by(IntegerType { 2 }).quotient);
  26. // base = base * base
  27. base.set_to(base.multiplied_by(base));
  28. }
  29. return exp;
  30. }
  31. UnsignedBigInteger GCD(UnsignedBigInteger const& a, UnsignedBigInteger const& b);
  32. UnsignedBigInteger LCM(UnsignedBigInteger const& a, UnsignedBigInteger const& b);
  33. UnsignedBigInteger random_number(UnsignedBigInteger const& min, UnsignedBigInteger const& max_excluded);
  34. bool is_probably_prime(UnsignedBigInteger const& p);
  35. UnsignedBigInteger random_big_prime(size_t bits);
  36. }