Repository navigation
Expand file tree
/
Copy pathone-click-rsa-cracker.py
More file actions
1977 lines (1611 loc) · 71.6 KB
/
Copy pathone-click-rsa-cracker.py
File metadata and controls
1977 lines (1611 loc) · 71.6 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
#!/usr/bin/env python3
"""
Enhanced RSA Cracking Tool
A comprehensive, automated tool for breaking RSA encryption using multiple attack vectors.
Just provide a public key, certificate, or ciphertext, and the tool will attempt all possible
attack methods to break the encryption.
Author: WhiskeyCoder
"""
import argparse
import base64
import binascii
import json
import math
import os
import re
import requests
import subprocess
import sys
import tempfile
import time
from typing import Dict, Tuple, List, Optional, Union, Any
from urllib.parse import quote_plus
class RSACrackingTool:
"""
Comprehensive tool for automatic RSA cryptanalysis.
"""
def __init__(self, verbose: bool = False, online_lookup: bool = True, max_workers: int = 4,
deep_scan: bool = False, timeout: int = 300):
"""
Initialize the RSA cracking tool.
Args:
verbose: Whether to print detailed information
online_lookup: Whether to use online services for factorization
max_workers: Maximum number of parallel workers for attacks
deep_scan: Whether to try more exhaustive/time-consuming attacks
timeout: Maximum time in seconds for each attack method
"""
self.verbose = verbose
self.online_lookup = online_lookup
self.max_workers = max_workers
self.deep_scan = deep_scan
self.timeout = timeout
# Track attempted attack methods
self.attempted_methods = set()
# Try to import optional dependencies
self.optional_deps = self._check_optional_dependencies()
def log(self, message: str, level: str = 'INFO') -> None:
"""Print a message if verbose mode is enabled or for important messages."""
if self.verbose or level in ['WARNING', 'ERROR', 'SUCCESS']:
prefix = f"[{level}]"
if level == 'SUCCESS':
prefix = "[✓]"
elif level == 'ERROR':
prefix = "[✗]"
elif level == 'WARNING':
prefix = "[!]"
print(f"{prefix} {message}")
def _check_optional_dependencies(self) -> Dict[str, bool]:
"""Check which optional dependencies are available."""
dependencies = {
'gmpy2': False,
'cryptography': False,
'sympy': False,
'pycryptodome': False,
'factordb': False,
'tqdm': False
}
# Try to import each dependency
try:
import gmpy2
dependencies['gmpy2'] = True
except ImportError:
pass
try:
import cryptography
dependencies['cryptography'] = True
except ImportError:
pass
try:
import sympy
dependencies['sympy'] = True
except ImportError:
pass
try:
import Crypto
dependencies['pycryptodome'] = True
except ImportError:
pass
try:
import factordb.factordb
dependencies['factordb'] = True
except ImportError:
pass
try:
import tqdm
dependencies['tqdm'] = True
except ImportError:
pass
return dependencies
# ===== Utility Methods =====
@staticmethod
def int_to_string(value: int) -> str:
"""
Convert an integer to its string representation.
Args:
value: Integer to convert
Returns:
String representation of the integer
Raises:
ValueError: If the integer cannot be converted to a valid string
"""
try:
# Ensure the hex representation has an even number of digits
hex_string = format(value, "x")
if len(hex_string) % 2 != 0:
hex_string = '0' + hex_string
return binascii.unhexlify(hex_string.encode("utf-8")).decode("utf-8")
except (binascii.Error, UnicodeDecodeError) as e:
raise ValueError(f"Failed to convert integer to string: {str(e)}")
@staticmethod
def string_to_int(message: Union[str, bytes]) -> int:
"""
Convert a string or bytes to an integer representation.
Args:
message: Input string or bytes to convert
Returns:
Integer representation of the input
"""
if isinstance(message, str):
message = message.encode('utf-8')
return int(binascii.hexlify(message), 16)
@staticmethod
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Extended Euclidean Algorithm to find gcd(a, b) and coefficients x, y
such that ax + by = gcd(a, b).
Args:
a: First integer
b: Second integer
Returns:
Tuple of (gcd, x, y) where ax + by = gcd
"""
if a == 0:
return b, 0, 1
# Initialize variables
last_remainder, remainder = abs(a), abs(b)
x, last_x, y, last_y = 0, 1, 1, 0
# Compute extended GCD iteratively
while remainder:
quotient, remainder = divmod(last_remainder, remainder)
x, last_x = last_x - quotient * x, x
y, last_y = last_y - quotient * y, y
last_remainder = remainder
# Adjust signs based on input
return (
last_remainder,
last_x * (-1 if a < 0 else 1),
last_y * (-1 if b < 0 else 1)
)
@staticmethod
def mod_inverse(a: int, m: int) -> int:
"""
Calculate the modular multiplicative inverse of a modulo m.
Args:
a: Integer to find inverse for
m: Modulus
Returns:
Modular multiplicative inverse
Raises:
ValueError: If a and m are not coprime (inverse doesn't exist)
"""
gcd, x, y = RSACrackingTool.extended_gcd(a, m)
# Inverse exists only if gcd is 1
if gcd != 1:
raise ValueError(f"Modular inverse does not exist (gcd={gcd})")
# Ensure the result is in the range [0, m-1]
return x % m
@staticmethod
def is_prime(n: int, k: int = 10) -> bool:
"""
Check if a number is prime using Miller-Rabin primality test.
Args:
n: Number to check for primality
k: Number of test rounds (higher values increase accuracy)
Returns:
True if the number is probably prime, False otherwise
"""
import random
# Handle small cases
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
# Express n as 2^r * d + 1
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
# Witness loop
for _ in range(k):
a = random.randint(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
@staticmethod
def perfect_eth_root(n: int, e: int) -> Optional[int]:
"""
Check if n is a perfect eth power and return its eth root if true.
Args:
n: Number to check
e: Exponent to check
Returns:
The eth root of n if n is a perfect eth power, None otherwise
"""
# Try to use gmpy2 for better performance if available
try:
import gmpy2
root = gmpy2.iroot(n, e)
if root[1]: # iroot returns (root, is_exact)
return int(root[0])
return None
except ImportError:
pass
# Fallback to pure Python implementation
# Calculate an approximate root
root = round(n ** (1 / e))
# Check if this is indeed an eth root
if root ** e == n:
return root
# Try a few values around the approximation
for i in range(1, 1000):
if (root + i) ** e == n:
return root + i
if (root - i) ** e == n:
return root - i
return None
@staticmethod
def newton_method_root(n: int, k: int, precision: int = 100) -> int:
"""
Calculate the kth root of n using Newton's method.
Args:
n: The number to find the root of
k: The root to find (e.g., 2 for square root, 3 for cube root)
precision: Number of iterations for convergence
Returns:
The kth root of n as an integer
"""
u, s = n, n + 1
while u < s:
s = u
t = (k - 1) * s + n // pow(s, k - 1)
u = t // k
return s
# ===== Key Parsing Methods =====
def parse_pem_key(self, pem_data: str) -> Dict[str, int]:
"""
Parse a PEM-formatted RSA key file.
Args:
pem_data: The PEM key data
Returns:
Dictionary of RSA parameters
"""
# Try using cryptography library if available
if self.optional_deps['cryptography']:
try:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import load_pem_public_key, load_pem_private_key
try:
# Try as private key first
key = load_pem_private_key(pem_data.encode(), password=None, backend=default_backend())
if isinstance(key, rsa.RSAPrivateKey):
private_numbers = key.private_numbers()
public_numbers = private_numbers.public_numbers
return {
'n': public_numbers.n,
'e': public_numbers.e,
'd': private_numbers.d,
'p': private_numbers.p,
'q': private_numbers.q,
'dp': private_numbers.dmp1,
'dq': private_numbers.dmq1,
'qinv': private_numbers.iqmp,
}
except Exception:
pass
try:
# Try as public key
key = load_pem_public_key(pem_data.encode(), backend=default_backend())
if isinstance(key, rsa.RSAPublicKey):
public_numbers = key.public_numbers()
return {
'n': public_numbers.n,
'e': public_numbers.e
}
except Exception:
pass
except Exception as e:
self.log(f"Error parsing PEM with cryptography: {str(e)}", level="WARNING")
# Fallback to manual parsing
params = {}
# Check for public key format
modulus_match = re.search(r'Modulus:\s*([0-9a-fA-F:]+)', pem_data)
exponent_match = re.search(r'Exponent:\s*([0-9]+)', pem_data)
if modulus_match and exponent_match:
modulus_hex = modulus_match.group(1).replace(':', '')
params['n'] = int(modulus_hex, 16)
params['e'] = int(exponent_match.group(1))
return params
# Extract base64-encoded data
base64_data = ''
in_key = False
for line in pem_data.splitlines():
line = line.strip()
if line.startswith('-----BEGIN ') and line.endswith('-----'):
in_key = True
continue
if line.startswith('-----END ') and line.endswith('-----'):
in_key = False
continue
if in_key:
base64_data += line
if not base64_data:
raise ValueError("No base64-encoded key data found in PEM")
# Try to decode and extract parameters using ASN.1
try:
key_bytes = base64.b64decode(base64_data)
# Use PyCryptodome if available
if self.optional_deps['pycryptodome']:
try:
from Crypto.PublicKey import RSA
key = RSA.import_key(pem_data)
if key.has_private():
return {
'n': key.n,
'e': key.e,
'd': key.d,
'p': key.p,
'q': key.q
}
else:
return {
'n': key.n,
'e': key.e
}
except Exception as e:
self.log(f"Error parsing PEM with PyCryptodome: {str(e)}", level="WARNING")
# Fallback to basic ASN.1 parsing for common formats
# This is a simplified implementation and won't handle all cases
if key_bytes[0] == 0x30: # ASN.1 SEQUENCE
# Check if it's likely a public key
if b'\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01' in key_bytes: # OID for RSA
self.log("Detected RSA public key format in ASN.1 data", level="INFO")
# This is a rudimentary parser and won't work for all cases
pass
except Exception as e:
self.log(f"Failed to parse key bytes: {str(e)}", level="WARNING")
# If we couldn't parse anything
if not params:
raise ValueError("Failed to extract RSA parameters from PEM data")
return params
def parse_certificate(self, cert_data: str) -> Dict[str, int]:
"""
Parse an X.509 certificate to extract RSA parameters.
Args:
cert_data: The certificate data
Returns:
Dictionary of RSA parameters
"""
# Try using cryptography library if available
if self.optional_deps['cryptography']:
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
cert = x509.load_pem_x509_certificate(cert_data.encode(), default_backend())
pubkey = cert.public_key()
if isinstance(pubkey, rsa.RSAPublicKey):
public_numbers = pubkey.public_numbers()
return {
'n': public_numbers.n,
'e': public_numbers.e
}
except Exception as e:
self.log(f"Error parsing certificate with cryptography: {str(e)}", level="WARNING")
# Use OpenSSL as fallback
try:
with tempfile.NamedTemporaryFile(delete=False) as temp:
temp.write(cert_data.encode())
temp_name = temp.name
command = ['openssl', 'x509', '-in', temp_name, '-text', '-noout']
result = subprocess.run(command, capture_output=True, text=True)
os.unlink(temp_name)
if result.returncode == 0:
output = result.stdout
# Extract modulus
modulus_match = re.search(r'Modulus:\s*([0-9a-fA-F:]+)', output)
exponent_match = re.search(r'Exponent:\s*([0-9]+)', output)
if modulus_match and exponent_match:
modulus_hex = modulus_match.group(1).replace(':', '')
n = int(modulus_hex, 16)
e = int(exponent_match.group(1))
return {'n': n, 'e': e}
except Exception as e:
self.log(f"Error parsing certificate with OpenSSL: {str(e)}", level="WARNING")
raise ValueError("Failed to extract RSA parameters from certificate")
def parse_ssh_key(self, key_data: str) -> Dict[str, int]:
"""
Parse an SSH public key to extract RSA parameters.
Args:
key_data: The SSH key data
Returns:
Dictionary of RSA parameters
"""
# Check if it's an SSH public key format
if key_data.startswith('ssh-rsa'):
parts = key_data.split()
if len(parts) >= 2:
try:
key_bytes = base64.b64decode(parts[1])
# Parse the SSH key format
i = 0
# Skip the algorithm identifier
alg_len = int.from_bytes(key_bytes[i:i + 4], byteorder='big')
i += 4 + alg_len
# Extract e
e_len = int.from_bytes(key_bytes[i:i + 4], byteorder='big')
i += 4
e = int.from_bytes(key_bytes[i:i + e_len], byteorder='big')
i += e_len
# Extract n
n_len = int.from_bytes(key_bytes[i:i + 4], byteorder='big')
i += 4
n = int.from_bytes(key_bytes[i:i + n_len], byteorder='big')
return {'n': n, 'e': e}
except Exception as e:
self.log(f"Error parsing SSH key: {str(e)}", level="WARNING")
raise ValueError("Failed to extract RSA parameters from SSH key")
def detect_key_format(self, key_data: str) -> str:
"""
Detect the format of a key file.
Args:
key_data: The key data
Returns:
Format string ('pem', 'certificate', 'ssh', 'der', 'unknown')
"""
key_data = key_data.strip()
# Check for PEM format
if '-----BEGIN ' in key_data and '-----END ' in key_data:
if 'CERTIFICATE' in key_data:
return 'certificate'
return 'pem'
# Check for SSH public key
if key_data.startswith('ssh-rsa '):
return 'ssh'
# Check for numeric modulus/exponent format
if key_data.lower().startswith('n =') or key_data.lower().startswith('modulus ='):
return 'numeric'
# Might be DER format (binary)
if not all(c.isascii() and c.isprintable() for c in key_data):
return 'der'
return 'unknown'
def parse_key_file(self, file_path: str) -> Dict[str, int]:
"""
Parse an RSA key file in various formats.
Args:
file_path: Path to the key file
Returns:
Dictionary of RSA parameters
"""
try:
with open(file_path, 'r') as f:
data = f.read()
format_type = self.detect_key_format(data)
if format_type == 'pem':
return self.parse_pem_key(data)
elif format_type == 'certificate':
return self.parse_certificate(data)
elif format_type == 'ssh':
return self.parse_ssh_key(data)
elif format_type == 'numeric':
# Parse numeric format (e.g., n = ..., e = ...)
params = {}
lines = data.splitlines()
for line in lines:
line = line.strip()
if line.lower().startswith('n =') or line.lower().startswith('modulus ='):
value = re.sub(r'^[^=]+=\s*', '', line).strip()
if value.startswith('0x'):
params['n'] = int(value, 16)
else:
params['n'] = int(value)
elif line.lower().startswith('e =') or line.lower().startswith('exponent ='):
value = re.sub(r'^[^=]+=\s*', '', line).strip()
if value.startswith('0x'):
params['e'] = int(value, 16)
else:
params['e'] = int(value)
elif line.lower().startswith('d ='):
value = re.sub(r'^[^=]+=\s*', '', line).strip()
if value.startswith('0x'):
params['d'] = int(value, 16)
else:
params['d'] = int(value)
elif line.lower().startswith('p ='):
value = re.sub(r'^[^=]+=\s*', '', line).strip()
if value.startswith('0x'):
params['p'] = int(value, 16)
else:
params['p'] = int(value)
elif line.lower().startswith('q ='):
value = re.sub(r'^[^=]+=\s*', '', line).strip()
if value.startswith('0x'):
params['q'] = int(value, 16)
else:
params['q'] = int(value)
if 'n' in params and 'e' in params:
return params
# Try binary DER format as last resort
if format_type == 'der' or format_type == 'unknown':
try:
# Re-open in binary mode
with open(file_path, 'rb') as f:
data = f.read()
# Try PyCryptodome
if self.optional_deps['pycryptodome']:
from Crypto.PublicKey import RSA
key = RSA.import_key(data)
if key.has_private():
return {
'n': key.n,
'e': key.e,
'd': key.d,
'p': key.p,
'q': key.q
}
else:
return {
'n': key.n,
'e': key.e
}
except Exception as e:
self.log(f"Error parsing binary key: {str(e)}", level="WARNING")
except Exception as e:
self.log(f"Error reading or parsing key file: {str(e)}", level="ERROR")
raise ValueError(f"Failed to extract RSA parameters from {file_path}")
# ===== Factorization Methods =====
def trial_division(self, n: int, limit: int = 1_000_000) -> Optional[int]:
"""
Find a small prime factor of n using trial division.
Args:
n: Number to factor
limit: Maximum value to test for primality
Returns:
A small prime factor if found, None otherwise
"""
self.log(f"Attempting trial division up to {limit}...")
# Progress bar if tqdm is available
if self.optional_deps['tqdm']:
from tqdm import tqdm
iterator = tqdm(range(2, min(limit, int(math.sqrt(n)) + 1)))
else:
iterator = range(2, min(limit, int(math.sqrt(n)) + 1))
# Check if n is even
if n % 2 == 0:
return 2
# Check odd numbers up to the limit
for i in iterator:
if n % i == 0:
return i
return None
def pollard_rho(self, n: int, max_iterations: int = 100000) -> Optional[int]:
"""
Try to find a factor of n using Pollard's rho algorithm.
Args:
n: Number to factor
max_iterations: Maximum number of iterations
Returns:
A factor of n if found, None otherwise
"""
import random
self.log(f"Attempting Pollard's Rho algorithm...")
if n % 2 == 0:
return 2
# Define the function f(x) = (x^2 + c) % n
def f(x, c):
return (x * x + c) % n
# Progress updates for long-running iterations
update_interval = max(1, max_iterations // 100)
# Try different values of c if one fails
for c in range(1, 4):
x, y, d = 2, 2, 1
# Main loop
for i in range(max_iterations):
if i % update_interval == 0 and self.verbose:
print(f"Pollard Rho: iteration {i}/{max_iterations}, c={c}", end='\r')
x = f(x, c) # One step
y = f(f(y, c), c) # Two steps
d = math.gcd(abs(x - y), n)
if 1 < d < n:
self.log(f"\nFound factor with Pollard's Rho: {d}", level="SUCCESS")
return d
if d == n:
break # Failed with this c, try another
self.log(f"Pollard's Rho failed with c={c}")
return None
def pollard_p_minus_1(self, n: int, B1: int = 100000, B2: int = 1000000) -> Optional[int]:
"""
Try to find a factor of n using Pollard's p-1 algorithm.
Args:
n: Number to factor
B1: First bound
B2: Second bound
Returns:
A factor of n if found, None otherwise
"""
import random
self.log(f"Attempting Pollard's p-1 algorithm with B1={B1}, B2={B2}...")
# Try to use gmpy2 for better performance
if self.optional_deps['gmpy2']:
try:
import gmpy2
# Check if n is a perfect square
root_n = gmpy2.isqrt(n)
if gmpy2.is_square(n):
root = int(gmpy2.sqrt(n))
return (root, root)
# Fermat's method
a = root_n + 1
b2 = gmpy2.square(a) - n
for i in range(max_iterations):
if i % 1000 == 0 and self.verbose:
print(f"Fermat: iteration {i}/{max_iterations}", end='\r')
if gmpy2.is_square(b2):
b = gmpy2.sqrt(b2)
p = a + b
q = a - b
self.log(f"\nFound factorization with Fermat's method: {p}, {q}", level="SUCCESS")
return (int(p), int(q))
a += 1
b2 = gmpy2.square(a) - n
return None
except Exception as e:
self.log(f"Error in gmpy2 implementation of Fermat factorization: {str(e)}", level="WARNING")
# Fallback to pure Python implementation
a = math.isqrt(n) + 1
b2 = a * a - n
for i in range(max_iterations):
if i % 1000 == 0 and self.verbose:
print(f"Fermat: iteration {i}/{max_iterations}", end='\r')
b_root = math.isqrt(b2)
if b_root * b_root == b2:
p = a + b_root
q = a - b_root
self.log(f"\nFound factorization with Fermat's method: {p}, {q}", level="SUCCESS")
return (p, q)
a += 1
b2 = a * a - n
return None Stage 1
a = 2
for p in range(2, B1):
e = 1
while e <= B1 // p:
e *= p
a = gmpy2.powmod(a, e, n)
g = gmpy2.gcd(a - 1, n)
if 1 < g < n:
self.log(f"Found factor with Pollard's p-1 (stage 1): {g}", level="SUCCESS")
return int(g)
# Stage 2 (simplified)
if B2 > B1:
for p in range(B1, B2):
if gmpy2.is_prime(p):
a = gmpy2.powmod(a, p, n)
g = gmpy2.gcd(a - 1, n)
if 1 < g < n:
self.log(f"Found factor with Pollard's p-1 (stage 2): {g}", level="SUCCESS")
return int(g)
return None
except Exception as e:
self.log(f"Error in gmpy2 implementation of Pollard's p-1: {str(e)}", level="WARNING")
# Fallback to pure Python implementation
a = 2
# Stage 1
for p in range(2, B1):
# If using tqdm and verbose mode
if p % 1000 == 0 and self.verbose:
print(f"Pollard p-1: stage 1, testing prime {p}/{B1}", end='\r')
if self.is_prime(p):
e = 1
while e <= B1 // p:
e *= p
a = pow(a, e, n)
g = math.gcd(a - 1, n)
if 1 < g < n:
self.log(f"\nFound factor with Pollard's p-1 (stage 1): {g}", level="SUCCESS")
return g
# Stage 2 (simplified)
if B2 > B1:
for p in range(B1, min(B2, B1 + 10000)): # Limit to avoid excessive time
if p % 100 == 0 and self.verbose:
print(f"Pollard p-1: stage 2, testing prime {p}/{min(B2, B1 + 10000)}", end='\r')
if self.is_prime(p):
a = pow(a, p, n)
g = math.gcd(a - 1, n)
if 1 < g < n:
self.log(f"\nFound factor with Pollard's p-1 (stage 2): {g}", level="SUCCESS")
return g
return None
def fermat_factorization(self, n: int, max_iterations: int = 10000) -> Optional[Tuple[int, int]]:
"""
Try to factor n using Fermat's factorization method.
Args:
n: Number to factor
max_iterations: Maximum number of iterations
Returns:
Tuple of (p, q) if successful, None otherwise
"""
self.log(f"Attempting Fermat factorization...")
# Check if n is even
if n % 2 == 0:
return (2, n // 2)
# Try to use gmpy2 for better performance
if self.optional_deps['gmpy2']:
try:
import gmpy2
# Check if n is a perfect square
root_n = gmpy2.isqrt(n)
if gmpy2.is_square(n):
root = int(gmpy2.sqrt(n))
return (root, root)
# Fermat's method
a = root_n + 1
b2 = gmpy2.square(a) - n
for i in range(max_iterations):
if i % 1000 == 0 and self.verbose:
print(f"Fermat: iteration {i}/{max_iterations}", end='\r')
if gmpy2.is_square(b2):
b = gmpy2.sqrt(b2)
p = a + b
q = a - b
self.log(f"\nFound factorization with Fermat's method: {p}, {q}", level="SUCCESS")
return (int(p), int(q))
a += 1
b2 = gmpy2.square(a) - n
return None
except Exception as e:
self.log(f"Error in gmpy2 implementation of Fermat factorization: {str(e)}", level="WARNING")
# Fallback to pure Python implementation
a = math.isqrt(n) + 1
b2 = a * a - n
for i in range(max_iterations):
if i % 1000 == 0 and self.verbose:
print(f"Fermat: iteration {i}/{max_iterations}", end='\r')
b_root = math.isqrt(b2)
if b_root * b_root == b2:
p = a + b_root
q = a - b_root
self.log(f"\nFound factorization with Fermat's method: {p}, {q}", level="SUCCESS")
return (p, q)
a += 1
b2 = a * a - n
return None
def factorize_using_online_services(self, n: int) -> Optional[Tuple[int, int]]:
"""
Try to factorize n using online factorization services.
Args:
n: Number to factorize
Returns:
Tuple of (p, q) if successful, None otherwise
"""
if not self.online_lookup:
self.log("Online factorization services disabled", level="INFO")
return None
self.log("Attempting to factorize using online services...", level="INFO")
# Try FactorDB API if the library is available
if self.optional_deps['factordb']:
try:
from factordb.factordb import FactorDB
self.log("Using FactorDB API...", level="INFO")
f = FactorDB(n)
f.connect()
factors = f.get_factor_list()
if len(factors) == 2:
p, q = factors
self.log(f"Found factorization with FactorDB: {p}, {q}", level="SUCCESS")
return (p, q)
elif len(factors) > 2:
# If there are more than 2 factors, find p and q such that p*q = n
for i in range(len(factors)):
for j in range(i + 1, len(factors)):
if factors[i] * factors[j] == n:
self.log(f"Found factorization with FactorDB: {factors[i]}, {factors[j]}",
level="SUCCESS")
return (factors[i], factors[j])
self.log(f"FactorDB found {len(factors)} factors, but couldn't determine p and q", level="WARNING")
except Exception as e:
self.log(f"Error using FactorDB API: {str(e)}", level="WARNING")
# Try direct HTTP request to factordb.com
try:
self.log("Trying direct HTTP request to factordb.com...", level="INFO")
response = requests.get(f"http://factordb.com/index.php?query={n}")