forked from amitfinkel/RSA_project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa_functions.py
82 lines (68 loc) · 2.23 KB
/
rsa_functions.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
import random
import number_theory_functions as ntf
class RSA:
def __init__(self, public_key, private_key=None):
self.public_key = public_key
self.private_key = private_key
@staticmethod
def generate(digits=10):
"""
Creates an RSA encryption system object
Parameters
----------
digits : The number of digits N should have
Returns
-------
RSA: The RSA system containing:
* The public key (N,e)
* The private key (N,d)
"""
d = int(digits / 2)
p = None
q = None
while p is None or q is None or p == q or len(str(p * q)) != digits:
while p is None:
p = ntf.generate_prime(d)
while q is None:
q = ntf.generate_prime(digits - d)
if len(str(p * q)) != digits:
p = ntf.generate_prime(d)
q = ntf.generate_prime(digits - d)
N = p * q
k = (p - 1) * (q - 1)
e = random.choice(range(k))
while ntf.extended_gcd(e, k)[0] != 1:
e = random.choice(range(k))
d = ntf.modular_inverse(e, k)
public_key = (N, e)
private_key = (N, d)
return RSA(public_key=public_key, private_key=private_key)
@staticmethod
def calc_private_and_public(k):
e = random.choice(range(k))
while ntf.extended_gcd(e, k)[0] != 1:
e = random.choice(range(k))
d = ntf.modular_inverse(e, k)
return d, e
def encrypt(self, m):
"""
Encrypts the plaintext m using the RSA system
Parameters
----------
m : The plaintext to encrypt
Returns
-------
c : The encrypted ciphertext
"""
return ntf.modular_exponent(m, self.public_key[1], self.public_key[0])
def decrypt(self, c):
"""
Decrypts the ciphertext c using the RSA system
Parameters
----------
c : The ciphertext to decrypt
Returns
-------
m : The decrypted plaintext
"""
return ntf.modular_exponent(c, self.private_key[1], self.private_key[0])