public_key_cryptography course - challenge 8 - pourquoi utiliser 2 nombres premiers au lieu d'un\

je pensais qu'on prenait un nombre premier au carré, mais en fait il semble que le N du sujet est directement premier.
This commit is contained in:
boyreau 2026-11-14 13:24:19 +01:00
commit fbd5e62697
2 changed files with 29 additions and 2 deletions

View file

@ -16,6 +16,7 @@ from public_key_cryptography import (
decode,
hash_and_encrypt,
prime_factorization,
reverse_single_prime_RSA_cipher,
)
if __name__ == "__main__":
@ -42,5 +43,10 @@ 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))
# print(prime_factorization(510143758735509025530880200653196460532653147)) # too slow
print(reverse_single_prime_RSA_cipher(
161367550346730604451454756189028938964941280347662098798775466019463375610700074840105776873791605070092554650190486030367121011578171525759600774739890458414593857709994072516290998135846956596662071379067305011746842247628316996977338024343628757374524136260758515864509435302781735938531030576289086798942,
171731371218065444125482536302245915415603318380280392385291836472299752747934607246477508507827284075763910264995326010251268493630501989810855418416643352631102434317900028697993224868629935657273062472544675693365930943308086634291936846505861203914449338007760990051788980485462592823446469606824421932591,
65537
))
# fmt: on

View file

@ -1,5 +1,5 @@
from hashlib import sha256
from Crypto.Util.number import bytes_to_long
from Crypto.Util.number import bytes_to_long, long_to_bytes
from math import ceil, sqrt
@ -61,3 +61,24 @@ def Fermat(N: int) -> (int, int):
# Challenge PK-crypto-7
def prime_factorization(N: int):
return Fermat(N)
# Challenge PK-crypto-8
def _find_single_prime_RSA_private_key(N: int, d: int):
# N = x²
# p = sqrt(N) -> on factorise facilement p
# phi(N) = phi(p²) = p * (p-1)
# phi(N) = sqrt(N) * (sqrt(N) - 1) = p * (p - 1)
# d*e = 1 mod phi(N)
# Il ne reste plus qu'à trouver l'inverse modulaire de e mod Phi(N) pour avoir d
p = int(sqrt(N))
phi_N = p * (p - 1)
e = pow(d, -1, phi_N)
print(f"N: {N}, p: {p}, phi_N: {phi_N}, e: {e}")
return e
def reverse_single_prime_RSA_cipher(c: int, N: int, d: int):
# On calcule la clé privée puis on applique la formule de déchiffrement
e = _find_single_prime_RSA_private_key(N, d)
return long_to_bytes(pow(c, e, N))