Skip to content

Commit 47aca70

Browse files
authored
Create RSA.py
0 parents  commit 47aca70

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

RSA.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from random import randint, randrange
2+
def IS_PRIME(n):#Miller-Rabin primality check.
3+
k=10
4+
def check(a, s, d, n):
5+
x = pow(a, d, n)
6+
if x == 1:
7+
return True
8+
for i in xrange(s - 1):
9+
if x == n - 1:
10+
return True
11+
x = pow(x, 2, n)
12+
return x == n - 1
13+
s = 0
14+
d = n - 1
15+
16+
while d % 2 == 0:
17+
d >>= 1
18+
s += 1
19+
for i in xrange(k):
20+
a = randrange(2, n - 1)
21+
if not check(a, s, d, n):
22+
return False
23+
return True
24+
def KEYGEN():
25+
Key_P = randint(2**1023, 2**1024)#Initial pseudorandom value of P
26+
Key_Q = randint(2**1020, 2**1021)#Initial pseudorandom value of Q
27+
while not IS_PRIME(Key_P):#Primality check for P using IS_PRIME function
28+
Key_P = randint(2**1023, 2**1024)#Recalculation of pseudorandom value of P if not prime.
29+
while not IS_PRIME(Key_Q):#Primality check for Q using IS_PRIME function
30+
Key_Q = randint(2**1023, 2**1024)#Recalculation of pseudorandom value of Q if not prime.
31+
Key_N = Key_P * Key_Q#Calculation of n.
32+
Key_PhiN = (Key_P - 1) * (Key_Q - 1)#Calculation of phi(n).
33+
Key_E = randint(2, (Key_PhiN - 1))#Initial pseudorandom value of e.
34+
while not IS_PRIME(Key_E):#Primality check for E using IS_PRIME function.
35+
Key_E = randint(2, (Key_PhiN - 1))#Recalculation of pseudorandom value of e.
36+
OldRemainder = Key_E#Set OldRemainder to be equil to e.
37+
Remainder = Key_PhiN#Set Remainder to be equil to Phi of n.
38+
i = 0#Bezout coefficient variable, inital value.
39+
Oldi = 1#Previous value Bezout coefficient variable, inital value.
40+
while Remainder:#While a non-zero remainder is found in the long division below.
41+
OldRemainder, (Q, Remainder) = Remainder, divmod(OldRemainder, Remainder)#Paralell assignment of Q equals the quotient of the pair OldRemainder & Remainder via long division and OldRemainder now equals Remainder.
42+
i, Oldi = Oldi - Q*i, i#Paralell assignment Oldi equals i and i equals Oldi minus Q multiplied by i.
43+
Key_D = (Oldi % Key_PhiN)#Final calculation of d.
44+
return (Key_N, Key_E, Key_D)#Return values to be used as private and public keys.
45+
def MAIN():
46+
Plain_Text = "Hello World"#Plain text.
47+
Bytes_Plain_Text = str.encode(Plain_Text)#Plain text converted to bytes.
48+
Int_Plain_Text = int(Bytes_Plain_Text.encode('hex'), 16)#Plain text converted to Integer for printing.
49+
Key_N, Key_E, Key_D = KEYGEN()#Generate RSA keys.
50+
MAIN()

0 commit comments

Comments
 (0)