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

40 lines
924 B
Python

# Python Miller-Rabin implementation
import random
import lib.arithmetics as arithm
def get_d_and_s(n: int) -> (int, int):
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
return (d, s)
def rabin_witness(n: int, a: int) -> bool:
d, s = get_d_and_s(n)
x = arithm.modpow(a, d, n)
if x == 1 or x == n - 1:
return False
for _ in range(s - 1):
x = arithm.modpow(x, 2, n)
if x == n - 1:
return False
return True
def miller_rabin(n: int, k: int) -> bool:
if n < 3: return False
for _ in range(k):
a = random.randint(2, n - 1)
if rabin_witness(n, a): return False
return True
def is_prime(n: int) -> bool:
return miller_rabin(n, 25)
def get_random_prime(n: int) -> int:
a = random.randint(2**(n-1), 2**(n) - 1)
while not is_prime(a):
a = random.randint(2**(n-1), 2**(n) - 1)
return a