2020-04-09 02:39:48 +04:30
|
|
|
/*
|
2021-04-23 00:43:01 +04:30
|
|
|
* Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
|
2020-04-09 02:39:48 +04:30
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-04-09 02:39:48 +04:30
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
2020-05-27 12:28:17 +02:00
|
|
|
#include <AK/Random.h>
|
2020-04-09 02:39:48 +04:30
|
|
|
#include <LibCrypto/BigInt/UnsignedBigInteger.h>
|
|
|
|
|
|
2023-07-11 13:49:08 -04:00
|
|
|
namespace Crypto::NumberTheory {
|
2020-04-23 03:03:05 +04:30
|
|
|
|
2022-04-01 20:58:27 +03:00
|
|
|
UnsignedBigInteger ModularInverse(UnsignedBigInteger const& a_, UnsignedBigInteger const& b);
|
|
|
|
|
UnsignedBigInteger ModularPower(UnsignedBigInteger const& b, UnsignedBigInteger const& e, UnsignedBigInteger const& m);
|
2020-04-09 02:39:48 +04:30
|
|
|
|
2020-06-04 22:46:18 +04:30
|
|
|
// Note: This function _will_ generate extremely huge numbers, and in doing so,
|
|
|
|
|
// it will allocate and free a lot of memory!
|
|
|
|
|
// Please use |ModularPower| if your use-case is modexp.
|
|
|
|
|
template<typename IntegerType>
|
2022-04-01 20:58:27 +03:00
|
|
|
static IntegerType Power(IntegerType const& b, IntegerType const& e)
|
2020-06-04 22:46:18 +04:30
|
|
|
{
|
|
|
|
|
IntegerType ep { e };
|
|
|
|
|
IntegerType base { b };
|
|
|
|
|
IntegerType exp { 1 };
|
|
|
|
|
|
2020-06-06 01:13:58 +01:00
|
|
|
while (!(ep < IntegerType { 1 })) {
|
2020-06-04 22:46:18 +04:30
|
|
|
if (ep.words()[0] % 2 == 1)
|
|
|
|
|
exp.set_to(exp.multiplied_by(base));
|
|
|
|
|
|
|
|
|
|
// ep = ep / 2;
|
2020-06-06 01:13:58 +01:00
|
|
|
ep.set_to(ep.divided_by(IntegerType { 2 }).quotient);
|
2020-06-04 22:46:18 +04:30
|
|
|
|
|
|
|
|
// base = base * base
|
|
|
|
|
base.set_to(base.multiplied_by(base));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return exp;
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-01 20:58:27 +03:00
|
|
|
UnsignedBigInteger GCD(UnsignedBigInteger const& a, UnsignedBigInteger const& b);
|
|
|
|
|
UnsignedBigInteger LCM(UnsignedBigInteger const& a, UnsignedBigInteger const& b);
|
2020-04-09 02:39:48 +04:30
|
|
|
|
2022-04-01 20:58:27 +03:00
|
|
|
UnsignedBigInteger random_number(UnsignedBigInteger const& min, UnsignedBigInteger const& max_excluded);
|
|
|
|
|
bool is_probably_prime(UnsignedBigInteger const& p);
|
2020-08-15 23:20:33 +02:00
|
|
|
UnsignedBigInteger random_big_prime(size_t bits);
|
2020-04-23 03:03:05 +04:30
|
|
|
|
|
|
|
|
}
|