Repository navigation
Expand file tree
/
Copy pathRSA.cpp
More file actions
1012 lines (853 loc) · 30.4 KB
/
Copy pathRSA.cpp
File metadata and controls
1012 lines (853 loc) · 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// RSA Algorithm Implementation
//
#include "RSA.h"
#include "BigIntegerParallel.h"
#include "Montgomery.h"
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <cstdio>
#include <cstring>
#include <map>
#include <chrono>
#include <limits>
std::mt19937_64& RSA::rng()
{
thread_local std::mt19937_64 engine(
static_cast<uint64_t>(std::random_device{}()) ^
static_cast<uint64_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count()) ^
static_cast<uint64_t>(std::hash<std::thread::id>{}(std::this_thread::get_id())));
return engine;
}
uint32_t RSA::randomWord32()
{
static thread_local std::uniform_int_distribution<uint32_t> dist(
0, std::numeric_limits<uint32_t>::max());
return dist(rng());
}
BigInteger RSA::randomBits(size_t bitLength, bool ensureTopBit)
{
if (bitLength == 0)
return BigInteger(0);
size_t limbCount = (bitLength + 31) / 32;
BigInteger result;
result.digits.assign(limbCount, 0);
for (size_t i = 0; i < limbCount; ++i)
result.digits[i] = randomWord32();
size_t extraBits = limbCount * 32 - bitLength;
if (extraBits > 0)
{
uint32_t mask = static_cast<uint32_t>(0xFFFFFFFFu >> extraBits);
result.digits.back() &= mask;
}
if (ensureTopBit)
{
size_t bitIndex = bitLength - 1;
size_t limbIndex = bitIndex / 32;
size_t bitOffset = bitIndex % 32;
result.digits[limbIndex] |= (1U << bitOffset);
}
result.sign = false;
result.normalize();
return result;
}
BigInteger RSA::randomBelow(const BigInteger& limit)
{
if (limit.isZero())
return BigInteger(0);
size_t bits = MontgomeryReducer::bitLength(limit);
BigInteger candidate;
do
{
candidate = randomBits(bits, false);
candidate.normalize();
}
while (candidate > limit);
return candidate;
}
// Extended modulo operation for BigInteger (supports large modulus)
// Uses optimized binary long division
BigInteger RSA::mod(const BigInteger& a, const BigInteger& modulus) {
if (modulus.isZero()) {
throw runtime_error("Modulus cannot be zero");
}
BigInteger modAbs = modulus.getSign() ? modulus.absolute() : modulus;
BigInteger result = a % modAbs;
if (result.getSign()) {
result = result + modAbs;
}
return result;
}
// Modular exponentiation (fast exponentiation with parallel optimization)
BigInteger RSA::modPow(const BigInteger& base, const BigInteger& exp, const BigInteger& modulus) {
if (modulus.isZero()) {
throw runtime_error("Modulus cannot be zero");
}
MontgomeryReducer reducer(modulus);
return reducer.modPow(base, exp);
}
// Greatest Common Divisor
BigInteger RSA::gcd(const BigInteger& a, const BigInteger& b) {
BigInteger zero(0);
BigInteger x = a;
BigInteger y = b;
// Get absolute values
bool xSign = x.getSign();
bool ySign = y.getSign();
if (xSign) {
x = x.absolute();
}
if (ySign) {
y = y.absolute();
}
while (y != zero) {
BigInteger temp = y;
y = mod(x, y);
x = temp;
}
return x;
}
// Extended Euclidean Algorithm
pair<BigInteger, pair<BigInteger, BigInteger>> RSA::extendedGcd(const BigInteger& a, const BigInteger& b) {
BigInteger zero(0);
BigInteger one(1);
BigInteger b_copy = b;
if (b_copy == zero) {
BigInteger a_abs = a;
bool aSign = a_abs.getSign();
if (aSign) {
a_abs = a_abs.absolute();
}
return make_pair(a_abs, make_pair(one, zero));
}
BigInteger a_abs = a;
BigInteger b_abs = b;
bool aSign = a_abs.getSign();
bool bSign = b_abs.getSign();
if (aSign) {
a_abs = a_abs.absolute();
}
if (bSign) {
b_abs = b_abs.absolute();
}
auto result = extendedGcd(b_abs, mod(a_abs, b_abs));
BigInteger gcd_val = result.first;
BigInteger x1 = result.second.first;
BigInteger y1 = result.second.second;
BigInteger quotient = a_abs / b_abs;
BigInteger x = y1;
BigInteger quotient_times_y1 = quotient * y1;
BigInteger y = x1 - quotient_times_y1;
return make_pair(gcd_val, make_pair(x, y));
}
// Modular inverse using extended Euclidean algorithm
BigInteger RSA::modInverse(const BigInteger& a, const BigInteger& modulus) {
BigInteger one(1);
BigInteger zero(0);
auto result = extendedGcd(a, modulus);
BigInteger gcd_val = result.first;
if (gcd_val != one) {
throw runtime_error("Modular inverse does not exist");
}
BigInteger x = result.second.first;
BigInteger m_abs = modulus;
bool mSign = m_abs.getSign();
if (mSign) {
m_abs = m_abs.absolute();
}
// Make sure result is positive
x = mod(x, m_abs);
bool xSign = x.getSign();
if (xSign) {
x = x + m_abs;
}
bool xNeg = x < zero;
if (xNeg) {
x = x + m_abs;
}
return x;
}
// Generate random BigInteger with specified bit length
BigInteger RSA::randomBigInteger(int bitLength) {
if (bitLength <= 0) {
return BigInteger(0);
}
return randomBits(static_cast<size_t>(bitLength), true);
}
// Generate random BigInteger in range [min, max]
BigInteger RSA::randomBigInteger(const BigInteger& minVal, const BigInteger& maxVal) {
BigInteger zero(0);
BigInteger one(1);
BigInteger min_copy = minVal;
BigInteger max_copy = maxVal;
if (max_copy < min_copy) {
return min_copy;
}
BigInteger range = max_copy - min_copy;
if (range == zero) {
return min_copy;
}
BigInteger rangeInclusive = range;
BigInteger candidate;
do {
candidate = randomBelow(rangeInclusive);
} while (candidate > rangeInclusive);
return min_copy + candidate;
}
// Optimized Miller-Rabin primality test
bool RSA::millerRabin(const BigInteger& n, int iterations) {
BigInteger two(2);
BigInteger three(3);
BigInteger one(1);
BigInteger n_copy = n;
if (n_copy == two || n_copy == three) {
return true;
}
if (n_copy < two || !n_copy.isOdd()) {
return false;
}
BigInteger n_minus_one = n_copy - one;
BigInteger d = n_minus_one;
int r = 0;
while (!d.isOdd()) {
d = d / two;
++r;
}
size_t nBits = n_copy.bitLength();
if (nBits >= 1536) {
iterations = std::max(iterations, 64);
} else if (nBits >= 1024) {
iterations = std::max(iterations, 48);
} else if (nBits >= 512) {
iterations = std::max(iterations, 40);
} else if (nBits >= 256) {
iterations = std::max(iterations, 32);
} else {
iterations = std::max(iterations, 16);
}
vector<BigInteger> testBases;
if (nBits <= 64 && iterations <= 12) {
static const vector<int> deterministicBases = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
for (int i = 0; i < min(iterations, (int)deterministicBases.size()); ++i) {
testBases.push_back(BigInteger(deterministicBases[i]));
}
} else {
BigInteger n_minus_two = n_copy - two;
if (n_minus_two < two) {
n_minus_two = two;
}
for (int i = 0; i < iterations; ++i) {
BigInteger a = randomBigInteger(two, n_minus_two);
testBases.push_back(a);
}
}
MontgomeryReducer reducer(n_copy);
BigInteger montOne = reducer.toMontgomery(one);
BigInteger montNMinusOne = reducer.toMontgomery(n_minus_one);
for (const BigInteger& base : testBases) {
BigInteger candidate = base;
if (candidate >= n_copy) {
candidate = mod(candidate, n_copy);
}
if (candidate <= one) {
continue;
}
BigInteger baseMont = reducer.toMontgomery(candidate);
BigInteger xMont = reducer.powMontgomery(baseMont, d);
if (xMont == montOne || xMont == montNMinusOne) {
continue;
}
bool witnessComposite = true;
BigInteger xTempMont = xMont;
for (int j = 0; j < r - 1; ++j) {
xTempMont = reducer.multiply(xTempMont, xTempMont);
if (xTempMont == montNMinusOne) {
witnessComposite = false;
break;
}
if (xTempMont == montOne) {
return false;
}
}
if (witnessComposite) {
return false;
}
}
return true;
}
// Quick trial division with extended small primes
bool RSA::quickTrialDivision(const BigInteger& n, int maxDivisor) {
BigInteger zero(0);
BigInteger n_copy = n;
// Extended list of small primes for faster pre-screening
// First 168 primes (all primes < 1000)
static const vector<int> smallPrimes = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
};
for (int p : smallPrimes) {
if (p > maxDivisor) break;
BigInteger p_big(p);
if (n_copy == p_big) {
return true; // It's a small prime
}
if (mod(n_copy, p_big) == zero) {
return false; // Divisible by small prime
}
}
return true; // Passed trial division
}
// Fast prime check with optimized pre-screening
bool RSA::isPrimeFast(const BigInteger& n, int iterations) {
BigInteger two(2);
BigInteger zero(0);
BigInteger n_copy = n;
// Quick checks
if (n_copy < two) {
return false;
}
if (n_copy == two) {
return true;
}
if (!n_copy.isOdd()) {
return false;
}
// Fast trial division with extended small primes
if (!quickTrialDivision(n_copy, 1000)) {
return false;
}
// For very small numbers, use deterministic test
// If n < 2^64, we can use deterministic Miller-Rabin
// For our purposes, if bit length < 64, use more iterations for high confidence
int adjustedIterations = iterations;
if (n_copy.bitLength() <= 64) {
adjustedIterations = min(iterations * 2, 50);
}
return millerRabin(n_copy, adjustedIterations);
}
// Check if number is prime (using fast version)
bool RSA::isPrime(const BigInteger& n, int iterations) {
return isPrimeFast(n, iterations);
}
// Generate a prime number with specified bit length
BigInteger RSA::generatePrime(int bitLength,
std::chrono::steady_clock::time_point deadline) {
auto checkDeadline = [&]() {
if (std::chrono::steady_clock::now() >= deadline) {
throw runtime_error("RSA key generation timed out");
}
};
checkDeadline();
if (bitLength < 2) {
return BigInteger(2);
}
if (bitLength == 2) {
return BigInteger(3); // Only odd prime with 2 bits
}
// Calculate min and max values
BigInteger minVal("1");
for (int i = 0; i < bitLength - 1; i++) {
minVal = minVal * BigInteger(2);
}
BigInteger maxVal("1");
for (int i = 0; i < bitLength; i++) {
maxVal = maxVal * BigInteger(2);
}
maxVal = maxVal - BigInteger(1);
int maxAttempts = 5000; // Increased attempts for better success rate
int millerRabinIterations;
if (bitLength <= 64) {
millerRabinIterations = 16;
} else if (bitLength <= 128) {
millerRabinIterations = 24;
} else if (bitLength <= 256) {
millerRabinIterations = 32;
} else {
millerRabinIterations = 40;
}
for (int attempt = 0; attempt < maxAttempts; attempt++) {
checkDeadline();
BigInteger candidate = randomBigInteger(bitLength);
// Ensure candidate is in range and odd
if (candidate < minVal) {
candidate = minVal;
}
if (candidate > maxVal) {
candidate = maxVal;
}
if (!candidate.isOdd()) {
if (candidate < maxVal) {
candidate = candidate + BigInteger(1);
} else {
candidate = candidate - BigInteger(1);
}
}
checkDeadline();
// Test for primality
if (isPrime(candidate, millerRabinIterations)) {
return candidate;
}
// Try next odd number
if (attempt % 10 == 0 && candidate < maxVal - BigInteger(2)) {
candidate = candidate + BigInteger(2);
}
}
throw runtime_error("Failed to generate prime after maximum attempts");
}
// Optimized candidate generation using wheel sieve concept
BigInteger RSA::generateCandidateOptimized(int bitLength, const BigInteger& minVal,
const BigInteger& maxVal, mt19937& gen,
int attempt,
std::chrono::steady_clock::time_point deadline) {
if (std::chrono::steady_clock::now() >= deadline) {
throw runtime_error("RSA key generation timed out");
}
(void)gen;
(void)attempt;
BigInteger candidate = randomBigInteger(bitLength);
if (candidate < minVal) {
candidate = minVal;
}
if (candidate > maxVal) {
candidate = maxVal;
}
BigInteger two(2);
if (!candidate.isOdd()) {
if (candidate < maxVal) {
candidate = candidate + BigInteger(1);
} else if (candidate > minVal) {
candidate = candidate - BigInteger(1);
}
}
return candidate;
}
// Generate prime with specific seed for parallel generation (optimized)
BigInteger RSA::generatePrimeWithSeed(int bitLength,
unsigned int seed,
std::chrono::steady_clock::time_point deadline) {
auto checkDeadline = [&]() {
if (std::chrono::steady_clock::now() >= deadline) {
throw runtime_error("RSA key generation timed out");
}
};
checkDeadline();
if (bitLength < 2) {
return BigInteger(2);
}
if (bitLength == 2) {
return BigInteger(3);
}
// Calculate min and max values (cache these calculations)
static mutex cacheMutex;
static map<int, pair<BigInteger, BigInteger>> rangeCache;
BigInteger minVal, maxVal;
{
lock_guard<mutex> lock(cacheMutex);
auto it = rangeCache.find(bitLength);
if (it != rangeCache.end()) {
minVal = it->second.first;
maxVal = it->second.second;
} else {
minVal = BigInteger("1");
for (int i = 0; i < bitLength - 1; i++) {
minVal = minVal * BigInteger(2);
}
maxVal = BigInteger("1");
for (int i = 0; i < bitLength; i++) {
maxVal = maxVal * BigInteger(2);
}
maxVal = maxVal - BigInteger(1);
rangeCache[bitLength] = make_pair(minVal, maxVal);
}
}
// Optimized: reduce iterations for smaller keys, adjust based on bit length
int millerRabinIterations;
if (bitLength <= 64) {
millerRabinIterations = 16;
} else if (bitLength <= 128) {
millerRabinIterations = 24;
} else if (bitLength <= 256) {
millerRabinIterations = 32;
} else {
millerRabinIterations = 40;
}
int maxAttempts = 3000; // Reduced attempts due to better pre-screening
// int batchSize = min(BigIntegerParallel::getMaxThreads(), 6); // Batch size for parallel testing
// if (batchSize < 2) batchSize = 2;
int batchSize=16;
// Use thread-specific random number generator with seed
hash<thread::id> hasher;
size_t threadHash = hasher(this_thread::get_id());
auto now = chrono::high_resolution_clock::now();
auto nanos = chrono::duration_cast<chrono::nanoseconds>(now.time_since_epoch()).count();
unsigned int threadSeed = seed ^ (static_cast<unsigned int>(threadHash) << 16);
threadSeed ^= static_cast<unsigned int>(nanos % 1000000);
mt19937 gen(threadSeed);
BigInteger two(2);
BigInteger one(1);
// Wheel sieve: skip numbers divisible by small primes
// Use increments that avoid small prime factors
// For RSA primes, we mainly need to avoid 2 (already handled), 3, 5, 7
// Pattern: +2, +4, +2, +4, +2, +4, +6, +2, +6 (avoids 3, 5, 7)
static const vector<int> wheelIncrements = {2, 4, 2, 4, 2, 4, 6, 2, 6};
int wheelIndex = 0;
BigInteger currentCandidate;
bool hasCandidate = false;
int attempt = 0;
while (attempt < maxAttempts) {
checkDeadline();
vector<BigInteger> candidateBatch;
candidateBatch.reserve(batchSize);
// Generate a batch of candidates
for (int batch = 0; batch < batchSize && attempt < maxAttempts; ++batch, ++attempt) {
checkDeadline();
BigInteger candidate;
if (!hasCandidate || attempt % 10 == 0) {
// Generate new candidate every 10 attempts or initially
candidate = generateCandidateOptimized(bitLength, minVal, maxVal, gen, attempt, deadline);
currentCandidate = candidate;
hasCandidate = true;
wheelIndex = 0;
} else {
// Use wheel increments to skip likely composites
int increment = wheelIncrements[wheelIndex % wheelIncrements.size()];
wheelIndex++;
candidate = currentCandidate + BigInteger(increment * 2); // *2 because we only test odds
// Wrap around if exceeded max
if (candidate > maxVal) {
candidate = minVal + mod(candidate - minVal, maxVal - minVal + one);
// Ensure odd
if (!candidate.isOdd()) {
candidate = candidate + one;
}
}
currentCandidate = candidate;
}
candidateBatch.push_back(candidate);
}
// Launch parallel primality tests for the batch
vector<future<bool>> futures;
futures.reserve(candidateBatch.size());
for (const auto& candidate : candidateBatch) {
futures.push_back(async(launch::async, [candidate, millerRabinIterations]() {
if (!quickTrialDivision(candidate, 100)) {
return false;
}
return isPrimeFast(candidate, millerRabinIterations);
}));
}
// Collect results
for (size_t i = 0; i < candidateBatch.size(); ++i) {
checkDeadline();
if (futures[i].get()) {
return candidateBatch[i];
}
}
}
throw runtime_error("Failed to generate prime after maximum attempts");
}
// Parallel prime generation
BigInteger RSA::generatePrimeParallel(int bitLength,
int threadId,
std::chrono::steady_clock::time_point deadline) {
if (std::chrono::steady_clock::now() >= deadline) {
throw runtime_error("RSA key generation timed out");
}
// Use thread ID, time, and high-resolution clock to generate unique seed
hash<thread::id> hasher;
size_t threadHash = hasher(this_thread::get_id());
auto now = chrono::high_resolution_clock::now();
auto nanos = chrono::duration_cast<chrono::nanoseconds>(now.time_since_epoch()).count();
unsigned int seed = static_cast<unsigned int>(
threadId * 10000 +
(nanos % 1000000) +
(threadHash % 10000)
);
return generatePrimeWithSeed(bitLength, seed, deadline);
}
// Generate RSA key pair with parallel optimization
RSA::KeyPair RSA::generateKeyPair(int bitLength, std::chrono::milliseconds timeout) {
if (bitLength < 64) {
throw runtime_error("Bit length must be at least 64");
}
if (timeout <= std::chrono::milliseconds::zero()) {
throw runtime_error("Timeout must be positive");
}
int primeLength = bitLength / 2;
auto deadline = std::chrono::steady_clock::now() + timeout;
// Use parallel generation for p and q
// They can be generated independently, which approximately halves the generation time
future<BigInteger> futureP = async(launch::async, &RSA::generatePrimeParallel, primeLength, 1, deadline);
future<BigInteger> futureQ = async(launch::async, &RSA::generatePrimeParallel, primeLength, 2, deadline);
// Wait for both primes to be generated
BigInteger p = futureP.get();
BigInteger q = futureQ.get();
// Ensure p != q (extremely rare but handle it)
// If equal, regenerate one of them in parallel
if (p == q) {
// Regenerate q with a different seed
q = generatePrimeParallel(primeLength, 100, deadline);
// If still equal (extremely unlikely), try a few more times
int retryCount = 0;
while (p == q && retryCount < 5) {
future<BigInteger> futureQ2 = async(launch::async, &RSA::generatePrimeParallel, primeLength, 200 + retryCount, deadline);
q = futureQ2.get();
retryCount++;
}
}
if (p == q) {
throw runtime_error("Failed to generate distinct primes after multiple attempts");
}
// Calculate n = p * q
BigInteger n = p * q;
// Calculate phi(n) = (p-1) * (q-1)
BigInteger phi = (p - BigInteger(1)) * (q - BigInteger(1));
// Choose public exponent e (typically 65537)
BigInteger e = BigInteger(65537);
if (e >= phi || gcd(e, phi) != BigInteger(1)) {
// Try smaller e
e = BigInteger(3);
while (e < phi && gcd(e, phi) != BigInteger(1)) {
e = e + BigInteger(2);
}
}
// Calculate private exponent d = e^(-1) mod phi(n)
BigInteger d = modInverse(e, phi);
KeyPair keys;
keys.n = n;
keys.e = e;
keys.d = d;
keys.p = p;
keys.q = q;
return keys;
}
// Convert BigInteger to string (hexadecimal for compactness)
string RSA::bigIntegerToString(const BigInteger& num) {
BigInteger num_copy = num;
return string(num_copy);
}
// Convert string to BigInteger
BigInteger RSA::stringToBigInteger(const string& str) {
return BigInteger(str);
}
// Convert string to blocks
vector<BigInteger> RSA::stringToBlocks(const string& str, int blockSize) {
vector<BigInteger> blocks;
// Convert string to number: each byte becomes 2 hex digits
string hexStr;
for (char c : str) {
unsigned char uc = static_cast<unsigned char>(c);
char hex[3];
snprintf(hex, sizeof(hex), "%02x", uc);
hexStr += hex;
}
// Split into blocks
for (size_t i = 0; i < hexStr.length(); i += blockSize * 2) {
string blockHex = hexStr.substr(i, blockSize * 2);
if (blockHex.empty()) continue;
// Convert hex to decimal
BigInteger block = BigInteger(0);
BigInteger sixteen(16);
for (char c : blockHex) {
int digit = (c >= '0' && c <= '9') ? (c - '0') : (c - 'a' + 10);
if (digit < 0 || digit > 15) digit = 0;
BigInteger digitBig(digit);
BigInteger mult = block * sixteen;
block = mult + digitBig;
}
blocks.push_back(block);
}
return blocks;
}
// Convert blocks to string
string RSA::blocksToString(const vector<BigInteger>& blocks) {
string result;
for (const BigInteger& block : blocks) {
// Convert to hex
BigInteger temp = block;
string hexStr;
BigInteger zero = BigInteger(0);
BigInteger sixteen(16);
BigInteger temp_copy = temp;
if (temp_copy == zero) {
hexStr = "00";
} else {
while (temp > zero) {
BigInteger remainder = mod(temp, sixteen);
int digit = remainder.isZero() ? 0 : static_cast<int>(remainder.digits[0]);
if (digit < 0 || digit > 15) digit = 0;
char hexChar = (digit < 10) ? ('0' + digit) : ('a' + digit - 10);
hexStr = hexChar + hexStr;
temp = temp / sixteen;
}
// Ensure even length (each byte is 2 hex digits)
if (hexStr.length() % 2 != 0) {
hexStr = "0" + hexStr;
}
}
// Convert hex to bytes
for (size_t i = 0; i < hexStr.length(); i += 2) {
if (i + 1 < hexStr.length()) {
string byteHex = hexStr.substr(i, 2);
try {
int byteVal = stoi(byteHex, nullptr, 16);
result += static_cast<char>(byteVal);
} catch (...) {
// Skip invalid hex
}
}
}
}
// Remove trailing null bytes
while (!result.empty() && result.back() == '\0') {
result.pop_back();
}
return result;
}
// Encrypt message
string RSA::encrypt(const string& message, const BigInteger& n, const BigInteger& e) {
if (message.empty()) {
return "";
}
// Calculate maximum block size: n must be greater than the block value
// Each byte becomes 2 hex digits, so we need: blockSize * 2 <= log10(n) * log10(16)
// Conservative: use about 1/4 of modulus digits
BigInteger n_copy1 = n;
int modulusBits = static_cast<int>(n_copy1.bitLength());
int blockSize = (modulusBits / 8) - 1;
if (blockSize < 1) blockSize = 1;
if (blockSize > 100) blockSize = 100; // Limit block size
// Convert message to blocks
vector<BigInteger> blocks = stringToBlocks(message, blockSize);
// Encrypt each block
vector<string> encryptedBlocks;
BigInteger one(1);
BigInteger n_copy2 = n;
for (const BigInteger& block : blocks) {
// Ensure block is less than n
BigInteger blockMod = mod(block, n);
BigInteger n_minus_one = n_copy2 - one;
BigInteger n_copy3 = n;
if (blockMod >= n_copy3) {
blockMod = n_minus_one;
}
BigInteger encrypted = modPow(blockMod, e, n);
encryptedBlocks.push_back(bigIntegerToString(encrypted));
}
// Join blocks with delimiter
string result;
for (size_t i = 0; i < encryptedBlocks.size(); i++) {
if (i > 0) result += ":";
result += encryptedBlocks[i];
}
return result;
}
// Decrypt message
string RSA::decrypt(const string& ciphertext, const BigInteger& n, const BigInteger& d) {
if (ciphertext.empty()) {
return "";
}
// Split into blocks
vector<BigInteger> blocks;
stringstream ss(ciphertext);
string token;
while (getline(ss, token, ':')) {
if (!token.empty()) {
blocks.push_back(stringToBigInteger(token));
}
}
// Decrypt each block
vector<BigInteger> decryptedBlocks;
for (const BigInteger& block : blocks) {
BigInteger decrypted = modPow(block, d, n);
decryptedBlocks.push_back(decrypted);
}
// Convert blocks to string
return blocksToString(decryptedBlocks);
}
// Sign message
string RSA::sign(const string& message, const BigInteger& n, const BigInteger& d) {
if (message.empty()) {
return "";
}
// Create hash of message (simple: use message itself for small messages)
// For production, use proper hash function like SHA-256
string hash = message;
// Calculate block size (same as encryption)
BigInteger n_copy = n;
int modulusBits = static_cast<int>(n_copy.bitLength());
int blockSize = (modulusBits / 8) - 1;
if (blockSize < 1) blockSize = 1;
if (blockSize > 100) blockSize = 100;
// Convert to blocks and sign
vector<BigInteger> blocks = stringToBlocks(hash, blockSize);
vector<string> signatureBlocks;
BigInteger one(1);
BigInteger n_copy4 = n;
for (const BigInteger& block : blocks) {
// Ensure block is less than n
BigInteger blockMod = mod(block, n);
BigInteger n_minus_one = n_copy4 - one;
BigInteger n_copy5 = n;
if (blockMod >= n_copy5) {
blockMod = n_minus_one;
}
BigInteger signature = modPow(blockMod, d, n);
signatureBlocks.push_back(bigIntegerToString(signature));
}
// Join signature blocks
string result;
for (size_t i = 0; i < signatureBlocks.size(); i++) {
if (i > 0) result += ":";
result += signatureBlocks[i];
}
return result;
}
// Verify signature
bool RSA::verify(const string& message, const string& signature, const BigInteger& n, const BigInteger& e) {
if (message.empty() || signature.empty()) {
return false;
}
// Create hash of message
string hash = message;
// Decrypt signature
vector<BigInteger> signatureBlocks;
stringstream ss(signature);
string token;
while (getline(ss, token, ':')) {
if (!token.empty()) {
try {
signatureBlocks.push_back(stringToBigInteger(token));
} catch (...) {
return false;
}
}
}
if (signatureBlocks.empty()) {
return false;
}
// Verify each block
vector<BigInteger> verifiedBlocks;
for (const BigInteger& sigBlock : signatureBlocks) {
BigInteger verified = modPow(sigBlock, e, n);