-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.py
102 lines (79 loc) · 2.77 KB
/
rsa.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
from Crypto.Util.number import getPrime, inverse
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP
import math
class MyRSA:
def __init__(self, number_of_bits=1024, generate_keys=False):
if generate_keys:
self._mod, self._pub_exp, self._pvt_exp = self.generate_keys(number_of_bits)
self._num_bits = number_of_bits
@property
def num_bytes(self):
return self._num_bits // 8
@property
def pub_exp(self):
return self._pub_exp
@property
def pvt_exp(self):
return self._pvt_exp
@property
def mod(self):
return self._mod
@property
def keys(self):
return self._mod, self._pub_exp, self.pvt_exp
def set_keys(self, mod, pub_exp, pvt_exp):
self._mod, self._pub_exp, self._pvt_exp = mod, pub_exp, pvt_exp
@staticmethod
def generate_keys(number_of_bits=1024):
p = getPrime(number_of_bits // 2)
q = getPrime(number_of_bits // 2)
n = p * q
lcm = math.lcm(p-1, q-1)
e = MyRSA.random_coprime_below(lcm, number_of_bits // 2)
d = inverse(e, lcm)
return n, e, d
def encrypt(self, value):
return pow(value, self._pub_exp, self._mod)
def decrypt(self, value):
return pow(value, self._pvt_exp, self._mod)
@staticmethod
def random_coprime_below(max_val, number_of_bits):
result = getPrime(number_of_bits)
while result >= max_val or math.gcd(result, max_val) != 1:
result = getPrime(number_of_bits)
return result
class PyRSA:
def __init__(self, number_of_bits=1024, generate_keys=False):
if generate_keys:
self._mod, self._pub_exp, self._pvt_exp = self.generate_keys(number_of_bits)
self._num_bits = number_of_bits
@property
def num_bytes(self):
return self._num_bits // 8
@property
def pub_exp(self):
return self._pub_exp
@property
def pvt_exp(self):
return self._pvt_exp
@property
def mod(self):
return self._mod
@property
def keys(self):
return self._mod, self._pub_exp, self.pvt_exp
def set_keys(self, mod, pub_exp, pvt_exp):
self._mod, self._pub_exp, self._pvt_exp = mod, pub_exp, pvt_exp
@staticmethod
def generate_keys(number_of_bits=1024):
key = RSA.generate(number_of_bits)
return key.n, key.e, key.d
def encrypt(self, value):
key = RSA.construct(rsa_components=(self._mod, self._pub_exp, self._pvt_exp))
cipher = PKCS1_OAEP.new(key)
return cipher.encrypt(bytearray(value))
def decrypt(self, value):
key = RSA.construct(rsa_components=(self._mod, self._pub_exp, self._pvt_exp))
cipher = PKCS1_OAEP.new(key)
return cipher.decrypt(bytearray(value))