diff --git a/challenge.py b/challenge.py index 7ffee9a..fa5e340 100644 --- a/challenge.py +++ b/challenge.py @@ -15,6 +15,7 @@ from public_key_cryptography import ( private_key, decode, hash_and_encrypt, + prime_factorization, ) if __name__ == "__main__": @@ -41,4 +42,5 @@ if __name__ == "__main__": print(private_key(857504083339712752489993810777, 1029224947942998075080348647219, 0x10001)) print(decode(857504083339712752489993810777, 1029224947942998075080348647219, 0x10001, 77578995801157823671636298847186723593814843845525223303932)) print(hash_and_encrypt("crypto{Immut4ble_m3ssag1ng}")) + print(prime_factorization(510143758735509025530880200653196460532653147)) # fmt: on diff --git a/public_key_cryptography.py b/public_key_cryptography.py index 2e1a2c0..25e9e33 100644 --- a/public_key_cryptography.py +++ b/public_key_cryptography.py @@ -1,5 +1,6 @@ from hashlib import sha256 from Crypto.Util.number import bytes_to_long +from math import ceil, sqrt # Challenge PK-crypto-1 @@ -35,3 +36,28 @@ def hash_and_encrypt(m: str): m_bytes = m.encode("UTF-8") hash = bytes_to_long(sha256(m_bytes).digest()) return pow(hash, d, N) + + +# Repris du TP3 de math pour la crypto +def estCarre(x: int) -> bool: + return pow(ceil(sqrt(x)), 2) == x + + +def Fermat(N: int) -> (int, int): + """Find the prime factors of a number. + Args: + N: a prime product. + Returns: + p, q the prime factors of N. + """ + x = ceil(sqrt(N)) + while not estCarre(pow(x, 2) - N): + x += 1 + p = x + sqrt(pow(x, 2) - N) + q = x - sqrt(pow(x, 2) - N) + return (ceil(p), ceil(q)) + + +# Challenge PK-crypto-7 +def prime_factorization(N: int): + return Fermat(N)