ModularPower.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. * Copyright (c) 2020-2021, Dex♪ <dexes.ttp@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "UnsignedBigIntegerAlgorithms.h"
  8. namespace Crypto {
  9. void UnsignedBigIntegerAlgorithms::destructive_modular_power_without_allocation(
  10. UnsignedBigInteger& ep,
  11. UnsignedBigInteger& base,
  12. UnsignedBigInteger const& m,
  13. UnsignedBigInteger& temp_1,
  14. UnsignedBigInteger& temp_2,
  15. UnsignedBigInteger& temp_3,
  16. UnsignedBigInteger& temp_4,
  17. UnsignedBigInteger& temp_multiply,
  18. UnsignedBigInteger& temp_quotient,
  19. UnsignedBigInteger& temp_remainder,
  20. UnsignedBigInteger& exp)
  21. {
  22. exp.set_to(1);
  23. while (!(ep < 1)) {
  24. if (ep.words()[0] % 2 == 1) {
  25. // exp = (exp * base) % m;
  26. multiply_without_allocation(exp, base, temp_1, temp_2, temp_3, temp_multiply);
  27. divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  28. exp.set_to(temp_remainder);
  29. }
  30. // ep = ep / 2;
  31. divide_u16_without_allocation(ep, 2, temp_quotient, temp_remainder);
  32. ep.set_to(temp_quotient);
  33. // base = (base * base) % m;
  34. multiply_without_allocation(base, base, temp_1, temp_2, temp_3, temp_multiply);
  35. divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder);
  36. base.set_to(temp_remainder);
  37. // Note that not clamping here would cause future calculations (multiply, specifically) to allocate even more unused space
  38. // which would then persist through the temp bigints, and significantly slow down later loops.
  39. // To avoid that, we can clamp to a specific max size, or just clamp to the min needed amount of space.
  40. ep.clamp_to_trimmed_length();
  41. exp.clamp_to_trimmed_length();
  42. base.clamp_to_trimmed_length();
  43. }
  44. }
  45. }