forked from Unicuby/FMSI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfermat.py
54 lines (37 loc) · 1.18 KB
/
fermat.py
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
# -*- coding: utf-8 -*-
import math
from rsa import RSA
def factorisation_fermat(n):
if (n % 2 == 0):
return (-1, -1)
A = math.ceil(math.sqrt(n))
Bsq = A * A - n
sq = (int) (math.sqrt(Bsq))
while sq * sq != Bsq:
A = A + 1
Bsq = A * A - n
sq = (int) (math.sqrt(Bsq))
return (A - sq, A + sq)
def crack_primes(n):
p,q = factorisation_fermat(n)
if p == -1:
return None
return (p, q)
def crack_msg(msg, n):
primes = crack_primes(n)
if not primes:
print("Could not crack message with Fermat factorisation algorithm")
return None
(p, q) = primes
r = RSA.generate(p, q)
return r.decrypt(msg)
if __name__ == "__main__":
original_msg = "Hello, world! This is my very secret message."
print("Encrypting:", original_msg)
r = RSA.generate(661, 673)
encrypted_msg = r.encrypt(original_msg)
# print("Encrypted data:", encrypted_msg)
print(10 * '*', "Cracking with Fermat factorisation", 10 * '*')
cracked_msg = crack_msg(encrypted_msg, r.n)
print("Got:", cracked_msg)
print("Success!" if cracked_msg == original_msg else "Failure.")