Added Miller Rabin's algorithm:

- Now can generate a 4096-bit key in seconds.
	However, a longer key makes the cipher way too
	long. Should make a padding or an encoding to
	reduce the cipher size with big keys.

Signed-off-by: HeshamTB <hishaminv@gmail.com>
This commit is contained in:
HeshamTB 2020-04-18 18:34:36 +03:00
parent 06793f5fb7
commit 611a6c45ea
Signed by: Hesham
GPG Key ID: 74876157D199B09E
3 changed files with 33 additions and 1 deletions

30
MillerRabin.py Normal file
View File

@ -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

1
TODO
View File

@ -10,3 +10,4 @@ resources:
https://crypto.stackexchange.com/questions/1448/definition-of-textbook-rsa 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://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://www.inf.pucrs.br/~calazans/graduate/TPVLSI_I/RSA-oaep_spec.pdf
https://stackoverflow.com/questions/17298130/working-with-large-primes-in-python

3
rsa.py
View File

@ -13,6 +13,7 @@ https://crypto.stackexchange.com/questions/13113/how-can-i-find-the-prime-number
import math import math
import os import os
import sys import sys
import MillerRabin as mr
keysFolder = "keys/" keysFolder = "keys/"
byteOrder = "little" 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() #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) x = int.from_bytes(os.urandom(int(bits/8)), byteOrder)
print("trying: ", x, end="") print("trying: ", x, end="")
if isPrime(x): if mr.is_prime(x):
print("\nprime: ", x) print("\nprime: ", x)
return x return x
print("\r",end="") print("\r",end="")