RSA mit Python
Zur Navigation springen
Zur Suche springen
import random
import math
# Funktion zur Berechnung des größten gemeinsamen Teilers (GCD) von zwei Zahlen
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Funktion zur Berechnung des multiplikativen Inversen modulo m
def multiplicative_inverse(e, phi):
d = 0
x1, x2 = 0, 1
y1, y2 = 1, 0
phi_copy = phi
while e > 0:
quotient = phi_copy // e
phi_copy, e = e, phi_copy % e
x1, x2 = x2 - quotient * x1, x1
y1, y2 = y2 - quotient * y1, y1
if phi_copy == 1:
return y2 % phi
# Funktion zur Überprüfung, ob eine Zahl prim ist
def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
# Funktion zur Generierung eines RSA-Schlüsselpaars
def generate_rsa_keypair(bits):
p, q = 0, 0
# Wählen Sie zufällige Primzahlen p und q
while not (is_prime(p) and is_prime(q)):
p = random.getrandbits(bits)
q = random.getrandbits(bits)
n = p * q
phi = (p - 1) * (q - 1)
# Wählen Sie eine öffentliche Exponente (e)
e = random.randrange(1, phi)
while gcd(e, phi) != 1:
e = random.randrange(1, phi)
# Berechnen Sie das private Exponente (d)
d = multiplicative_inverse(e, phi)
return ((n, e), (n, d))
# Hauptprogramm
if __name__ == '__main__':
bits = 1024 # Bitlänge des RSA-Schlüsselpaares
public_key, private_key = generate_rsa_keypair(bits)
print("Öffentlicher Schlüssel (n, e):", public_key)
print("Privater Schlüssel (n, d):", private_key)