-
Notifications
You must be signed in to change notification settings - Fork 1
/
RSA.py
223 lines (147 loc) · 6.17 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ressources.prng as prng
import ressources.utils as ut
import ressources.bytesManager as bm
import ressources.interactions as it
import ressources.multGroup as multGroup
import ressources.config as config
import random as rd
# The RSA algorithm involves four steps: key generation, key distribution, encryption, and decryption.
#############################################
########### - Key Generation - ##############
#############################################
def key_gen(size: int = 2048, randomFunction=None, saving=False, Verbose=False):
"""
RSA key generation.
n: number of bits for safe prime generation.\n
randomFunction: prng choosen for random prime number generation (default = randbits from secrets module).
As a transitional measure, the use of RSA-based signature and confidentiality mechanisms with a key size of at least 2000 bits remain conform for the year 2023.
saving: True if you want to save the private key to a file.
"""
sizeB = size // 2
# 1- Choose two distinct prime numbers p and q
if Verbose:
print(f"Let's try to generate two distinct prime numbers p and q of {size} bits.")
p, q = prng.randomPrime(sizeB, randomFunction, Verbose=Verbose), prng.randomPrime(sizeB, randomFunction, Verbose=Verbose)
# 2- Compute n = pq.
n = p * q # new modulus
# 3- Compute λ(n), where λ is Carmichael's totient function.
# since p and q are prime, λ(p) = φ(p) = p − 1 and likewise λ(q) = q − 1. Hence λ(n) = lcm(p − 1, q − 1).
carmichaelTotient = ut.lcm(p - 1, q - 1)
# 4- Choosing e, part of the public key
e = rd.randrange(1, carmichaelTotient)
while not ut.coprime(e, carmichaelTotient) or bm.hammingWeight(e) > (0.995 * sizeB):
e = rd.randrange(1, carmichaelTotient)
# e having a short bit-length and small Hamming weight results in more efficient encryption
# https://en.wikipedia.org/wiki/Hamming_weight
# 5- Chossing d, modular multiplicative inverse of e modulo carmichaelTotient(n)
d = multGroup.inv(e, carmichaelTotient) # Private Key exponent
# p, q, and λ(n) must also be kept secret because they can be used to calculate d. In fact, they can all be discarded after d has been computed.
del p, q, carmichaelTotient
public_key, private_key = (n, e), (n, d)
if saving:
public_key = it.writeKeytoFile(public_key, "public_key", config.DIRECTORY_PROCESSING, ".kpk")
it.writeKeytoFile(private_key, "private_key", config.DIRECTORY_PROCESSING, ".kpk")
if Verbose:
print("\nYour private key has been generated Bob, keep it safe and never distibute them !")
print("\nThe public key has been generated, send this to your Alice: ", end="")
it.prGreen(public_key)
if not saving:
return (public_key, private_key)
#############################################
############# - Encryption - ################
#############################################
def encrypt(M: bytes, publicKey, saving: bool = False):
"""
Encrypt a message M to make him sendable.
"""
assert isinstance(M, bytes)
n, e = publicKey
def process(m):
return ut.square_and_multiply(m, e, n)
# First, turn M into int
Mint = bm.bytes_to_int(M)
if Mint < n:
# That's a short message
m = Mint
e = process(m)
else:
# M is a longer message, so it's divided into blocks
size = (it.getKeySize(publicKey) // 8) - 1
e = [process(bm.bytes_to_int(elt)) for elt in bm.splitBytes(M, size)]
if saving:
e = it.writeKeytoFile(e, "encrypted", config.DIRECTORY_PROCESSING, ".kat")
return e
#############################################
############# - Decryption - ################
#############################################
def decrypt(c, privateKey: tuple, asTxt=False):
"""
Decryption of given ciphertext 'c' with secret key 'privateKey'.
Return bytes/bytearray or txt if asTxt set to 'True'.
"""
n, d = privateKey
def process(cipherT):
un = ut.square_and_multiply(cipherT, d, n)
return bm.mult_to_bytes(un)
if isinstance(c, list):
decrypted = [process(elt) for elt in c]
r = bm.packSplittedBytes(decrypted)
else:
r = process(c)
if asTxt:
return r.decode()
return r
#############################################################
################ - Signature scheme - #######################
#############################################################
def signing(M: bytes, privateK: tuple = None, saving: bool = False, Verbose: bool = False):
"""
Signing the message (M).
You need to attach this signature to the message.
"""
assert isinstance(M, bytes)
from ..hashbased import hashFunctions as hashF
if not privateK:
privateK = it.extractKeyFromFile("private_key")
size = it.getKeySize(privateK) # Get key size
if Verbose:
print("Hashing in progress...")
hm = hashF.sponge(M, size)
# base64 to int
hm = bm.bytes_to_int(bm.mult_to_bytes(hm))
if Verbose:
print(f"hm = {hm}")
print("Hashing done.\n")
# raises it to the power of d (modulo n)
# same thing as decrypting
n, d = privateK
sign = ut.square_and_multiply(hm, d, n)
if saving:
sign = it.writeKeytoFile(sign, "RSA_signature")
return sign
def verifying(M: bytes, sign: int, pK: tuple = None):
"""
Verify given signature of message M with corresponding public key's.
"""
assert isinstance(M, (bytes, bytearray))
from ..hashbased import hashFunctions as hashF
if not pK:
pK = it.extractKeyFromFile("public_key")
size = it.getKeySize(pK)
hm = hashF.sponge(M, size)
# base64 to int
hm = bm.bytes_to_int(bm.mult_to_bytes(hm))
# If the signature is in base64
if not isinstance(sign, int):
sign = it.getIntKey(sign)
n, e = pK
# raises the signature to the power of e (modulo n)
# (as when encrypting a message)
if sign > n:
print("Signature > modulus")
test = ut.square_and_multiply(sign, e, n)
if test == (hm % n):
return True
return False