public_key_cryptography course - challenge 7 - prime factorization - result retrieved from factordb because a Fermat implementation in python is too slow to run it on my machine

This commit is contained in:
boyreau 2026-11-14 13:02:10 +01:00
commit 965057128d
2 changed files with 28 additions and 0 deletions

View file

@ -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)