Certainly! Here's a Python script that can factorize an RSA key given the public modulus and exponent as input:
import math
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def find_factor(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return i
return None
def factorize_rsa(n, e):
p = find_factor(n)
if p is None:
print("Failed to factorize the modulus.")
return None, None
q = n // p
if not is_prime(p) or not is_prime(q):
print("The modulus is not a product of two primes.")
return None, None
return p, q
# Example usage
modulus = int(input("Enter the RSA public modulus: "))
exponent = int(input("Enter the RSA public exponent: "))
p, q = factorize_rsa(modulus, exponent)
if p is not None and q is not None:
print(f"The factors of the RSA modulus are: p = {p} and q = {q}")
This script does the following:
-
We define a function is_prime(num) that checks if a given number is prime. It returns True if the number is prime and False otherwise.
-
We define a function find_factor(n) that finds a factor of the given number n. It iterates from 2 to the square root of n and checks if any number divides n evenly. If a factor is found, it is returned; otherwise, None is returned.
-
We define the main function factorize_rsa(n, e) that takes the RSA public modulus n and public exponent e as input.
-
Inside factorize_rsa(), we first call find_factor(n) to find a factor of the modulus. If no factor is found, we print an error message and return None, None.
-
If a factor p is found, we calculate the other factor q by dividing n by p.
-
We then check if both p and q are prime using the is_prime() function. If either of them is not prime, we print an error message and return None, None.
-
If both p and q are prime, we return them as the factors of the RSA modulus.
-
In the example usage section, we prompt the user to enter the RSA public modulus and exponent.
-
We call the factorize_rsa() function with the provided modulus and exponent.
-
If the factors p and q are successfully found, we print them; otherwise, the appropriate error message will be displayed.
Note: This script uses a simple factorization method and may not be efficient for large RSA moduli. It is suitable for educational purposes and small-scale demonstrations. For real-world RSA key factorization, more advanced algorithms and techniques are used.