ModularFunctions.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 {
  10. namespace NumberTheory {
  11. UnsignedBigInteger ModularInverse(const UnsignedBigInteger& a_, const UnsignedBigInteger& b);
  12. UnsignedBigInteger ModularPower(const UnsignedBigInteger& b, const UnsignedBigInteger& e, const UnsignedBigInteger& m);
  13. // Note: This function _will_ generate extremely huge numbers, and in doing so,
  14. // it will allocate and free a lot of memory!
  15. // Please use |ModularPower| if your use-case is modexp.
  16. template<typename IntegerType>
  17. static IntegerType Power(const IntegerType& b, const IntegerType& e)
  18. {
  19. IntegerType ep { e };
  20. IntegerType base { b };
  21. IntegerType exp { 1 };
  22. while (!(ep < IntegerType { 1 })) {
  23. if (ep.words()[0] % 2 == 1)
  24. exp.set_to(exp.multiplied_by(base));
  25. // ep = ep / 2;
  26. ep.set_to(ep.divided_by(IntegerType { 2 }).quotient);
  27. // base = base * base
  28. base.set_to(base.multiplied_by(base));
  29. }
  30. return exp;
  31. }
  32. UnsignedBigInteger GCD(const UnsignedBigInteger& a, const UnsignedBigInteger& b);
  33. UnsignedBigInteger LCM(const UnsignedBigInteger& a, const UnsignedBigInteger& b);
  34. UnsignedBigInteger random_number(const UnsignedBigInteger& min, const UnsignedBigInteger& max_excluded);
  35. bool is_probably_prime(const UnsignedBigInteger& p);
  36. UnsignedBigInteger random_big_prime(size_t bits);
  37. }
  38. }