diff --git a/MillerRabin.py b/MillerRabin.py new file mode 100644 index 0000000..8f89609 --- /dev/null +++ b/MillerRabin.py @@ -0,0 +1,30 @@ +#From: https://stackoverflow.com/questions/17298130/working-with-large-primes-in-python +from random import randrange +def is_prime(n, k=10): + if n == 2: + return True + if not n & 1: + return False + + def check(a, s, d, n): + x = pow(a, d, n) + if x == 1: + return True + for i in range(s - 1): + if x == n - 1: + return True + x = pow(x, 2, n) + return x == n - 1 + + s = 0 + d = n - 1 + + while d % 2 == 0: + d >>= 1 + s += 1 + + for i in range(k): + a = randrange(2, n - 1) + if not check(a, s, d, n): + return False + return True \ No newline at end of file diff --git a/TODO b/TODO index 3c5fe29..90e8be2 100644 --- a/TODO +++ b/TODO @@ -10,3 +10,4 @@ resources: https://crypto.stackexchange.com/questions/1448/definition-of-textbook-rsa https://crypto.stackexchange.com/questions/3608/why-is-padding-used-for-rsa-encryption-given-that-it-is-not-a-block-cipher https://www.inf.pucrs.br/~calazans/graduate/TPVLSI_I/RSA-oaep_spec.pdf + https://stackoverflow.com/questions/17298130/working-with-large-primes-in-python diff --git a/rsa.py b/rsa.py index 02ea1e2..4df10b3 100755 --- a/rsa.py +++ b/rsa.py @@ -13,6 +13,7 @@ https://crypto.stackexchange.com/questions/13113/how-can-i-find-the-prime-number import math import os import sys +import MillerRabin as mr keysFolder = "keys/" byteOrder = "little" @@ -135,7 +136,7 @@ def getPrime(bits): #Byte order "little" or "big" does not matter here since we want a random number from os.urandom() x = int.from_bytes(os.urandom(int(bits/8)), byteOrder) print("trying: ", x, end="") - if isPrime(x): + if mr.is_prime(x): print("\nprime: ", x) return x print("\r",end="")