7 std::variant<modular_arithmetic_error, bytes>
modexp(
const bytes& _base,
const bytes& _exponent,
const bytes& _modulus)
9 if (_modulus.size() == 0) {
13 auto output =
bytes(_modulus.size(),
'\0');
15 mpz_t base, exponent, modulus;
16 mpz_inits(base, exponent, modulus,
nullptr);
19 mpz_import(base, _base.size(), 1, 1, 0, 0, _base.data());
22 if (_exponent.size()) {
23 mpz_import(exponent, _exponent.size(), 1, 1, 0, 0, _exponent.data());
26 mpz_import(modulus, _modulus.size(), 1, 1, 0, 0, _modulus.data());
28 if (mpz_sgn(modulus) == 0) {
29 mpz_clears(base, exponent, modulus,
nullptr);
36 mpz_powm(result, base, exponent, modulus);
38 mpz_export(output.data(),
nullptr, -1, 1, 0, 0, result);
40 std::reverse(output.begin(), output.end());
42 mpz_clears(base, exponent, modulus, result,
nullptr);