-
Notifications
You must be signed in to change notification settings - Fork 6
/
RSA_module.py
76 lines (69 loc) · 1.83 KB
/
RSA_module.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from __future__ import unicode_literals
from math import sqrt
import random
from random import randint as rand
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def mod_inverse(a, m):
for x in range(1, m):
if (a * x) % m == 1:
return x
return -1
def isprime(n):
if n < 2:
return False
elif n == 2:
return True
else:
for i in range(1, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
def generate_keypair(keysize):
p = rand(1, 1000)
q = rand(1, 1000)
nMin = 1 << (keysize - 1)
nMax = (1 << keysize) - 1
primes = [2]
start = 1 << (keysize // 2 - 1)
stop = 1 << (keysize // 2 + 1)
if start >= stop:
return []
for i in range(3, stop + 1, 2):
for p in primes:
if i % p == 0:
break
else:
primes.append(i)
while (primes and primes[0] < start):
del primes[0]
while primes:
p = random.choice(primes)
primes.remove(p)
q_values = [q for q in primes if nMin <= p * q <= nMax]
if q_values:
q = random.choice(q_values)
break
print(p, q)
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(1, phi)
g = gcd(e, phi)
while True:
e = random.randrange(1, phi)
g = gcd(e, phi)
d = mod_inverse(e, phi)
if g == 1 and e != d:
break
return ((e, n), (d, n))
def encrypt(msg_plaintext, package):
e, n = package
msg_ciphertext = [pow(ord(c), e, n) for c in msg_plaintext]
return ''.join(map(lambda x: str(x), msg_ciphertext)), msg_ciphertext
def decrypt(msg_ciphertext, package):
d, n = package
msg_plaintext = [chr(pow(c, d, n)) for c in msg_ciphertext]
return (''.join(msg_plaintext))