python-rsa-implementation/lib/rsa.py
2025-01-23 17:57:15 +01:00

35 lines
841 B
Python

# Python RSA implementation
import random
import sys
import lib.arithmetics as arithm
import lib.miller_rabin as miller
def get_p_and_q(n: int) -> (int, int):
# Get two random prime numbers
p = miller.get_random_prime(n)
q = miller.get_random_prime(n)
# Ensure the two numbers are differents
while p == q:
q = get_random_prime(n)
return (p, q)
def get_keys(l: int) -> int:
p, q = get_p_and_q(l // 2)
n = p * q
phy_n = (p - 1) * (q - 1)
e = 65537
while arithm.gcd(e, phy_n) != 1:
p, q = get_p_and_q(l // 2)
n = p * q
phy_n = (p - 1) * (q - 1)
d = arithm.mod_inverse(e, phy_n)
return (e, d, n)
def encrypt(m: int, e: int, n: int) -> int:
return arithm.modpow(m, e, n)
def decrypt(c: int, d: int, n: int) -> int:
return arithm.modpow(c, d, n)