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("Factorization successful!")
print("p =", p)
print("q =", q)
This script does the following:
-
We define a function is_prime(num) that checks if a given number is prime. It iterates from 2 to the square root of the number and checks if any number divides the given number evenly. If no such number is found, it returns True, indicating that the number is prime.
-
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, it returns None.
-
The main function factorize_rsa(n, e) takes the RSA public modulus n and exponent e as input. It attempts to factorize the modulus by calling find_factor(n). If a factor is found, it is assigned to p, and q is calculated as n // p.
-
We check if both p and q are prime using the is_prime() function. If either of them is not prime, it means the modulus is not a product of two primes, and we return None, None.
-
If the factorization is successful and 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 then call the factorize_rsa() function with these values.
-
If the factorization is successful, we print a success message along with the values of p and q.
Note that this script uses a simple factorization method and may not be efficient for large RSA moduli. For larger moduli, more advanced factorization algorithms or techniques like the General Number Field Sieve (GNFS) would be required.
Also, keep in mind that factorizing an RSA modulus is considered a computationally infeasible task for properly chosen large primes, which is the basis of the security of the RSA cryptosystem.