Repository navigation
Expand file tree
/
Copy pathcripto.py
More file actions
327 lines (225 loc) · 6.86 KB
/
Copy pathcripto.py
File metadata and controls
327 lines (225 loc) · 6.86 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import secrets
import os
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography import exceptions
"""
Generate nonce
Returns
16-byte-long-random bytearray to be used as nonce
"""
def generateNonce():
return secrets.token_bytes(16)
"""
Encrypt message with the provided Public Key
The padding part is extracted from an example in Cryptography's Docs
OAEP padding is the recommended choice for new protocols/applications.
Args:
publicKey: Cryptography's Serialized Public Key object
message: message to be encrypted
Returns:
Encrypted message
"""
def encryptWithPublicKey(publicKey, message):
return publicKey.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
"""
Decrypt packets encrypted with the Public Key schemes
The padding part is extracted from an example in Cryptography's Docs
OAEP padding is the recommended choice for new protocols/applications.
Args:
packet: Encrypted packet to be decrypted
Returns:
Decrypted message
"""
def decryptWithPrivateKey(privateKey, message):
return privateKey.decrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
"""
Verify if the packet was signed with the provided Public Key
Args:
publicKey: Bytearray of the Sender's Public Key
message: Message signed with corresponding Sender's Private Key
signature: Signature of the message
Returns:
Wheter it was signed by the corresponding Private Key or not.
"""
def verifySignature(publicKey, message, signature):
matchesSignature = True
# Load Client's Public Key Object
if isinstance(publicKey, bytes):
publicKey = serialization.load_pem_public_key(publicKey)
try:
publicKey.verify(
signature,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
except exceptions.InvalidSignature:
matchesSignature = False
return matchesSignature
"""
Apply a message authentication code to a message using a key. To create the tag
we are using the SHA256 Hash function.
Args:
key: A 32 byte string
message: A common string
Returns:
The tag, A.K.A. MAC (Message Authentication Code)
"""
def createTag(key, message):
h = hmac.HMAC(key, hashes.SHA256())
if isinstance(message, str):
message = message.encode()
h.update(message)
# return b"".join([message, h.finalize()]) # to get the message with the MAC appended
return h.finalize() # to get only the MAC
"""
Verify if a message's MAC is valid, given a pre-shared key. To create the tag
we are using the SHA256 Hash function.
Args:
key: A 32 byte string
message: A byte string
sentMAC: A byte string
Returns:
It returns True if the MAC is valid or False if it isn't
"""
def verifyTag(key, sentMessage, sentTag):
h = hmac.HMAC(key, hashes.SHA256())
messageAsBytes = sentMessage
h.update(messageAsBytes)
try:
h.verify(sentTag)
return True
except exceptions.InvalidSignature:
return False
"""
Apply a SHA256 function to create a Digest of the message.
Args:
message: A bytearray to be digested
Return:
A message digest
"""
def createDigest(message):
digest = hashes.Hash(hashes.SHA256())
if isinstance(message, str):
message = message.encode()
digest.update(message)
return digest.finalize()
"""
Verify if the message's digest matches the given tag
Args:
message: A bytearray to be checked against the tag
tag: A bytearray representing the tag to be verified against
Return:
Wheter the tag matches or not the digest.
"""
def verifyDigest(message, tag):
return tag == createDigest(message)
"""
Use the master key to create two others keys, that are going to be used to
encryption and MAC
Args:
masterKey: A 32 byte key in byte format
salt: A 16 byte salt in byte format
Returns:
Two 32 byte keys[Symmetric, HMAC]
"""
def generateKeysWithMS(masterKey, salt):
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=64,
salt=salt,
info=b"",
)
bigKey = hkdf.derive(masterKey)
return bigKey[:(len(bigKey)//2)], bigKey[(len(bigKey)//2):]
"""
Generate a random master key of 256 bits (32 Bytes)
Returns:
It returns a master key in byte format
"""
def generateMasterKey():
return os.urandom(32)
"""
Generate a 32 byte key to be used in MAC
Returns:
It returns a key in byte format
"""
def generateMACKey():
return os.urandom(32)
"""
Generate a 16 byte salt
Returns:
Salt
"""
def generateSalt():
return os.urandom(16)
"""
Sign message with Client's Private Key
Args:
message: message to be signed
Returns:
Message Signature
"""
def signMessage(privateKey, message):
return privateKey.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
"""
Generate a Symmetric Key.
Returns:
A Symetric Key
"""
def generateSymmetricKey():
return os.urandom(32)
"""
Encrypt a message with a Key.
Args:
key: A key that will be used for encryption
nonce: Nonce used to encrypt the message in bytes
message: Message to be encrypted in bytes
Returns:
Encrypted message
"""
def encryptMessageWithKeyAES(key, nonce, message):
cipher = Cipher(algorithms.AES(key), modes.CTR(nonce))
encryptor = cipher.encryptor()
return encryptor.update(message) + encryptor.finalize()
"""
Decrypt a message with Symmetric Key.
Args:
key: A key that will be used for decryption
nonce: Nonce used to encrypt the message in bytes
message: Encrypted message in bytes
Returns:
Message decrypted
"""
def decryptMessageWithKeyAES(key, nonce, message):
cipher = Cipher(algorithms.AES(key), modes.CTR(nonce))
decryptor = cipher.decryptor()
return decryptor.update(message) + decryptor.finalize()