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