AES-DH Implementation
Loading...
Searching...
No Matches
prime.h
1#pragma once
2
3#include <cmath> // For std::sqrt()
4#include <cstdlib> // For randomness.
5#include <cstdint> // For fixed width integers.
6
14namespace prime {
15
21 inline bool is(const uint64_t& num) {
22 if (num == 1) return false;
23
24 // We only need to check up to the square root of the number in order to know if it's prime.
25 auto root = static_cast<uint64_t>(std::sqrt(num)) + 1;
26
27 // Start at 2, so we don't get a 0/1 false positive.
28 for (size_t x = 2; x <= root; ++x) {
29 if (num % x == 0)
30 return false;
31 }
32 return true;
33 }
34
35
44 template <typename T = uint64_t> inline void next(T& num) {
45 // Get to an odd number.
46 if (num % 2 == 0) num++;
47
48 // Loop until we find one.
49 for (; !prime::is(num); num += 2) {}
50 }
51
52
64 inline uint64_t raise(uint64_t value, uint64_t exp, const uint64_t& mod) {
65 uint64_t ret = 1;
66
67 // Ensure it's bounded by the mod.
68 value = value % mod;
69
70 // March down the exponent until it's been 0d.
71 while (exp > 0) {
72
73 // If the current bit is 1, multiply ret by our value, and mod it.
74 if (exp & 1) ret = (ret*value) % mod;
75
76 // Shift exp down.
77 exp = exp >> 1;
78 value = (value*value) % mod;
79 }
80 return ret;
81 }
82
83
93 inline std::pair<uint64_t, uint64_t> generate() {
94 auto q = static_cast<uint32_t>(std::rand());
96
97 // Sometime's q will not be prime, due to casting.
98 // We can just re-roll the number if that's the case.
99 auto p = (static_cast<uint64_t>(q) * 2) + 1;
100 if (!prime::is(p)) {
101 return prime::generate();
102 }
103 return {p, q};
104 }
105}
The namespace for prime number related operations.
Definition prime.h:14
bool is(const uint64_t &num)
Checks if any given number is prime.
Definition prime.h:21
std::pair< uint64_t, uint64_t > generate()
Generates a prime number.
Definition prime.h:93
void next(T &num)
Find the next prime greater than the provided number.
Definition prime.h:44
uint64_t raise(uint64_t value, uint64_t exp, const uint64_t &mod)
A O(logn) raise operation that works within modulus to prevent overflow.
Definition prime.h:64