-
Notifications
You must be signed in to change notification settings - Fork 3
/
aes_lib.py
634 lines (499 loc) · 23.7 KB
/
aes_lib.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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
#!/usr/bin/env python
import binascii, struct
from cryptopals_lib import *
class AES():
#Constants
#Generated by
'''
round_constants = "\x00"
for x in range(10):
if round_constants[x] >= "\x80":
round_constants[x+1] = round_constants[x] *2
else:
round_constants[x+1] = fixed_xor((round_constants[x] *2), '\x1b')
'''
round_constants = bytearray([0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f,0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4,0xb3,0x7d,0xfa,0xef,0xc5,0x91])
#Initial state of the Sbox (256 bytes) From definition
sbox = bytearray([0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
0x2c, 0x1a, 0x1b, 0x6e, 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, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60,
0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b,
0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
0x21, 0x0c, 0x7d])
def __init__(self, key, cipher="ECB"):
#self.key = key
self.cipher_name = cipher
#Get Keysize for AES 128/192/256
self.keysize = len(key)
#print("Keysize: {}".format(self.keysize))
#Block Size is static for AES
self.block_size = 16
self._setup_keysize_info()
#Static blocksize of 4x4
#Doesn't depend on the key
self.state = [bytes(4) for i in range(4)]
self.rounds_keys = self._key_expantion(key)
#self._printkey_expantion(self.rounds_keys)
def _setup_keysize_info(self):
if self.keysize == 16:
self.rounds = 10
self.words = 4
self.key_expantion_size = self.keysize * 11
elif self.keysize == 24:
self.rounds = 12
self.words = 6
self.key_expantion_size = self.keysize * 11
elif self.keysize == 32:
self.rounds = 14
self.words = 8
self.key_expantion_size = self.keysize * (self.rounds +1)
else:
raise ValueError("Invalid key size %d".format(self.keysize))
def _printkey_expantion(self, keys):
row_size = len(keys) // 4
for x in range(4):
print(' '.join('{:02X}'.format(a) for a in keys[(x*row_size):((x+1)*row_size)-1]))
def _key_expantion(self, key, row_idx=4):
row_size = self.key_expantion_size // row_idx
tmp_array = bytearray([0x00 for i in range(row_idx)])
round_keys = bytearray(self.key_expantion_size)
#Setup first key
for idx in range(row_idx):
round_keys[(idx*row_size):(idx*row_size)+ self.words] = [key[(row_idx*x) + idx] for x in range(self.words)]
#self._printkey_expantion(round_keys)
#print("")
#self._printkey_expantion(round_keys)
#Setup rest of the keys
for column_num in range(self.words, row_size):
#Reset round_xor per column
round_xor = bytearray([0x00 for i in range(row_idx)])
#Set up temp array for Key Round expansion
for idx in range(row_idx):
tmp_array[idx] = round_keys[(row_size*idx )+ column_num -1]
#print('Temp: ' + ' '.join('{:02X}'.format(a) for a in tmp_array))
#First round of the Next key
if column_num % self.words == 0:
#Rotate Word
#Take last column and shift top to bottom
tmp_array = tmp_array[1:] + tmp_array[:1]
#print('After Rotate Word: ' + ' '.join('{:02X}'.format(a) for a in tmp_array))
#Sub Bytes
#Take the index from the sbox
tmp_array = [self.sbox[tmp_array[idx]] for idx in range(row_idx)]
#print('After Sub Bytes: ' + ' '.join('{:02X}'.format(a) for a in tmp_array))
#Set Round_xor
round_xor[0] = self.round_constants[(column_num//self.words)]
#print('Rcon: ' + ' '.join('{:02X}'.format(a) for a in round_xor))
#Specific case for 256 bit key
elif self.keysize == 32 and column_num % self.words == 4:
#Sub Bytes
#Take the index from the sbox
tmp_array = [self.sbox[tmp_array[idx]] for idx in range(row_idx)]
#print('After Sub Bytes: ' + ' '.join('{:02X}'.format(a) for a in tmp_array))
#Xor the rmp_array and the round_xor
for idx in range(row_idx):
tmp_array[idx] ^= round_xor[idx]
#print('After Rcon: ' + ' '.join('{:02X}'.format(a) for a in tmp_array))
#XOR the tmp_array and the column_num-3
for idx in range(row_idx):
round_keys[(row_size*idx )+ column_num] = (tmp_array[idx] ^ round_keys[(row_size*idx )+ column_num -self.words])
#print("{:02X} ^ {:02X}".format(tmp_array[idx], round_keys[(row_size*idx )+ column_num -self.words]))
#self._printkey_expantion(round_keys)
return round_keys
def _sub_bytes(self, input_bytes):
output_bytes = bytearray()
#Use the input_bytes as an index to lookup what to substitute from the sbox index.
for lookup in input_bytes:
output_bytes.append(self.sbox[lookup])
return output_bytes
def _shift_rows(self, input_byte_array, idx=4):
#No swap for row 1
input_byte_array[0:idx] = input_byte_array[0:idx]
#Rotate once for row 2
input_byte_array[idx:(idx*2)] = input_byte_array[idx+1:(idx*2)] + input_byte_array[idx:idx+1]
#Rotate twice for row 3
input_byte_array[(idx*2):(idx*3)] = input_byte_array[(idx*2)+2:(idx*3)] + input_byte_array[(idx*2):(idx*2)+2]
#Rotate thrice for row 4
#print(input_byte_array[(idx*3)+3:(idx*4)] + input_byte_array[(idx*3):(idx*4)-1])
input_byte_array[(idx*3):(idx*4)] = input_byte_array[(idx*3)+3:(idx*4)] + input_byte_array[(idx*3):(idx*4)-1]
return input_byte_array
def _mix_columns(self, input_num):
matrix_mult_row = [2,3,1,1]
mix_output = bytearray(16)
#First
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[0] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[1] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[2] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[3] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
#Rotate the matrix_mult_row
matrix_mult_row = matrix_mult_row[-1:] + matrix_mult_row[:-1]
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[4] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[5] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[6] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[7] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
#Rotate the matrix_mult_row
matrix_mult_row = matrix_mult_row[-1:] + matrix_mult_row[:-1]
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[8] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[9] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[10] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[11] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
#Rotate the matrix_mult_row
matrix_mult_row = matrix_mult_row[-1:] + matrix_mult_row[:-1]
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[12] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[13] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[14] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[15] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
return mix_output
def _gmult(self, input_num, mult_parm):
#for the reverse parts
if mult_parm == 0x09:
#Change from 9 to 2x2x2+1
return self._gmult(self._gmult(self._gmult(input_num, 2), 2), 2) ^ input_num
elif mult_parm == 0x0b:
#Change from 11 to (2x2+1)x2+1
return (self._gmult((self._gmult(self._gmult(input_num, 2), 2) ^ input_num), 2) ^ input_num)
elif mult_parm == 0x0d:
#Change from 13 to (2+1)x2x2+1
return (self._gmult(self._gmult((self._gmult(input_num, 2) ^ input_num), 2), 2) ^ input_num)
elif mult_parm == 0x0e:
#Change from 15 to ((2+1)x2+1)x2
return self._gmult((self._gmult((self._gmult(input_num, 2) ^ input_num), 2) ^ input_num), 2)
output_num = 0
if mult_parm & 1 == 1:
#mult_parm is a 1 or a 3
output_num = input_num
if mult_parm & 2 == 2:
#mult_parm is a 2
if input_num & 0x80:
#If high bit is set
output_num ^= (input_num << 1) ^ 0x1b
else:
#if high bit it not set
output_num ^= (input_num << 1)
return output_num & 0xFF
def _add_round_key(self, input_bytes, round_index, row_idx=4):
row_size = self.key_expantion_size // row_idx
#Make Round Key
round_key = self.rounds_keys[(0*row_size)+(row_idx*round_index):(0*row_size)+(row_idx*round_index)+row_idx]
round_key += self.rounds_keys[(1*row_size)+(row_idx*round_index):(1*row_size)+(row_idx*round_index)+row_idx]
round_key += self.rounds_keys[(2*row_size)+(row_idx*round_index):(2*row_size)+(row_idx*round_index)+row_idx]
round_key += self.rounds_keys[(3*row_size)+(row_idx*round_index):(3*row_size)+(row_idx*round_index)+row_idx]
#print("k_sch[{}]: {}".format(round_index, round_key))
#Xor the input bytes with the previous round key
for idx in range(len(input_bytes)):
input_bytes[idx] ^= round_key[idx]
return input_bytes
def _reverse_shift_rows(self, input_byte_array, idx=4):
#No swap for row 1
input_byte_array[0:idx] = input_byte_array[0:idx]
#Rotate back once for row 2
input_byte_array[idx:(idx*2)] = input_byte_array[(idx*2)-1:(idx*2)] + input_byte_array[idx:(idx*2)-1]
#Rotate back twice for row 3
input_byte_array[(idx*2):(idx*3)] = input_byte_array[(idx*2)+2:(idx*3)] + input_byte_array[(idx*2):(idx*2)+2]
#Rotate back thrice for row 4
input_byte_array[(idx*3):(idx*4)] = input_byte_array[(idx*3)+1:(idx*4)] + input_byte_array[(idx*3):(idx*3)+1]
return input_byte_array
def _reverse_sub_bytes(self, input_bytes):
output_bytes = bytearray()
#Use the input_bytes as an index to lookup what to substitute from the inverted_sbox index.
for lookup in input_bytes:
output_bytes.append(self.inverted_sbox[lookup])
return output_bytes
def _reverse_mix_columns(self, input_num):
matrix_mult_row = [14,11,13,9]
mix_output = bytearray(16)
#First
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[0] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[1] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[2] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[3] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
#Rotate the matrix_mult_row
#print(matrix_mult_row)
matrix_mult_row = matrix_mult_row[-1:] + matrix_mult_row[:-1]
#print(matrix_mult_row)
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[4] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[5] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[6] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[7] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
#Rotate the matrix_mult_row
matrix_mult_row = matrix_mult_row[-1:] + matrix_mult_row[:-1]
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[8] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[9] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[10] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[11] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
#Rotate the matrix_mult_row
matrix_mult_row = matrix_mult_row[-1:] + matrix_mult_row[:-1]
for x in range(4):
#print("Index: {}".format((x*4)+(i%4)))
mix_output[12] ^= self._gmult(input_num[(x*4)], matrix_mult_row[x])
mix_output[13] ^= self._gmult(input_num[(x*4)+1], matrix_mult_row[x])
mix_output[14] ^= self._gmult(input_num[(x*4)+2], matrix_mult_row[x])
mix_output[15] ^= self._gmult(input_num[(x*4)+3], matrix_mult_row[x])
#print(mix_output)
return mix_output
def aes_block_encryption(self, plaintext):
if len(plaintext) != 16:
raise ValueError('wrong block length')
#Fix mapping
#print("plaintxt: {}".format(binascii.hexlify(plaintext)))
plaintext = bytearray([ plaintext[0],plaintext[4],plaintext[8],plaintext[12],
plaintext[1],plaintext[5],plaintext[9],plaintext[13],
plaintext[2],plaintext[6],plaintext[10],plaintext[14],
plaintext[3],plaintext[7],plaintext[11],plaintext[15]])
temp = self._add_round_key(plaintext, 0)
#print("After Add Rounds: {}, length: {}".format(temp, len(temp)))
#Do the first 9 rounds
for x in range(1, self.rounds):
#Do Sub Bytes
temp = self._sub_bytes(temp)
#print("s_box[{}]: {}".format(x, binascii.hexlify(temp)))
#Do ShiftRows
temp = self._shift_rows(temp)
#print("s_row[{}]: {}".format(x, binascii.hexlify(temp)))
#Do Mix Columns
temp = self._mix_columns(temp)
#print("m_col[{}]: {}".format(x, binascii.hexlify(temp)))
#Do Round Key
temp = self._add_round_key(temp, x)
#print("k_sch[{}]: {}".format(x, binascii.hexlify(temp)))
#Do last round
#Do Sub Bytes
temp = self._sub_bytes(temp)
#print("s_box[{}]: {}".format(self.rounds, binascii.hexlify(temp)))
#Do ShiftRows
temp = self._shift_rows(temp)
#print("s_row[{}]: {}".format(self.rounds, binascii.hexlify(temp)))
#Do Round Key
temp = self._add_round_key(temp, self.rounds)
#unbox to output
#print("result: {}".format(binascii.hexlify(temp)))
temp = bytearray([ temp[0],temp[4],temp[8],temp[12],
temp[1],temp[5],temp[9],temp[13],
temp[2],temp[6],temp[10],temp[14],
temp[3],temp[7],temp[11],temp[15]])
#print("result: {}".format(binascii.hexlify(temp)))
return temp
def aes_block_decryption(self, ciphertext):
if len(ciphertext) != 16:
raise ValueError('wrong block length')
#Fix mapping
ciphertext = bytearray([ciphertext[0],ciphertext[4],ciphertext[8],ciphertext[12],
ciphertext[1],ciphertext[5],ciphertext[9],ciphertext[13],
ciphertext[2],ciphertext[6],ciphertext[10],ciphertext[14],
ciphertext[3],ciphertext[7],ciphertext[11],ciphertext[15]])
#print("plaintxt: {}".format(binascii.hexlify(ciphertext)))
temp = self._add_round_key(ciphertext, self.rounds)
#print("After Add Rounds: {}, length: {}".format(temp, len(temp)))
#Do the reverse_add_round_key 9-0
for x in range(self.rounds-1,0,-1):
#Do ShiftRows
temp = self._reverse_shift_rows(temp)
#print("s_row[{}]: {}".format(self.rounds-x, binascii.hexlify(temp)))
#Do Sub Bytes
temp = self._reverse_sub_bytes(temp)
#print("s_box[{}]: {}".format(self.rounds-x, binascii.hexlify(temp)))
#Do Round Key
temp = self._add_round_key(temp, x)
#print("k_sch[{}]: {}".format(self.rounds-x, binascii.hexlify(temp)))
#Do Mix Columns
temp = self._reverse_mix_columns(temp)
#print("m_col[{}]: {}".format(self.rounds-x, binascii.hexlify(temp)))
#print("After Add Rounds: {}, length: {}".format(temp, len(temp)))
#Do last round
#Do ShiftRows
temp = self._reverse_shift_rows(temp)
#print("s_row[{}]: {}".format(self.rounds, binascii.hexlify(temp)))
#Do ShiftRows
temp = self._reverse_sub_bytes(temp)
#print("s_box[{}]: {}".format(self.rounds, binascii.hexlify(temp)))
#Do Round Key
temp = self._add_round_key(temp, 0)
#unbox to output
temp = bytearray([ temp[0],temp[4],temp[8],temp[12],
temp[1],temp[5],temp[9],temp[13],
temp[2],temp[6],temp[10],temp[14],
temp[3],temp[7],temp[11],temp[15]])
#print("result: {}".format(binascii.hexlify(temp)))
return temp
#Add Different Cipher Modes
def ctr_decryption(self, nonce, plaintext, little_endian=True):
return self.ctr_encryption(nonce, plaintext, little_endian)
def ctr_encryption(self, nonce, plaintext, little_endian=True):
counter = 0
cipher_blocks = []
for plain_block in to_blocks(plaintext, self.block_size):
if len(nonce) == self.block_size:
counter_nonce = fixedlen_xor(nonce, int_to_bytes_length(counter, self.block_size, False))
else:
counter_nonce = nonce + int_to_bytes_length(counter, (self.block_size - len(nonce)), False)
#print(counter_nonce)
aes_block = self.aes_block_encryption(counter_nonce)
#print(aes_block)
cipher_blocks.append(shortest_xor(aes_block, plain_block))
counter += 1
#Merge Cipher Blocks
return combind_blocks(cipher_blocks)
def ofb_encryption(self, init_iv, plaintext):
plain_blocks = to_blocks(plaintext, self.block_size)
previous_block = init_iv
cipher_blocks = []
for plain_block in plain_blocks:
aes_block = self.aes_block_encryption(previous_block)
cipher_blocks.append(fixedlen_xor(aes_block, plain_block))
previous_block = aes_block
#Merge Cipher Blocks
return combind_blocks(cipher_blocks)
def ofb_decryption(self, ciphertext):
#First Block is the IV
cipher_blocks = to_blocks(ciphertext, self.block_size)
previous_block = cipher_blocks[0]
plain_blocks = []
for cipher_block in cipher_blocks[1:]:
aes_block = self.aes_block_encryption(previous_block)
plain_blocks.append(fixedlen_xor(aes_block, cipher_block))
previous_block = aes_block
#Merge Cipher Blocks
return combind_blocks(plain_blocks)
def cfb_encryption(self, init_iv, plaintext):
#First Block is the IV
plain_blocks = to_blocks(plaintext, self.block_size)
cipher_blocks = [init_iv]
for plain_block in plain_blocks:
aes_block = self.aes_block_encryption(cipher_blocks[-1])
cipher_blocks.append(fixedlen_xor(aes_block, plain_block))
#Merge Cipher Blocks
return combind_blocks(cipher_blocks[1:])
def cfb_decryption(self, ciphertext):
#First Block is the IV
cipher_blocks = to_blocks(ciphertext, self.block_size)
previous_block = cipher_blocks[0]
plain_blocks = []
for cipher_block in cipher_blocks[1:]:
aes_block = self.aes_block_encryption(previous_block)
plain_blocks.append(fixedlen_xor(aes_block, cipher_block))
previous_block = cipher_block
#Merge Cipher Blocks
return combind_blocks(plain_blocks)
def cbc_encryption(self, init_iv, plaintext):
#First Block is the IV
plain_blocks = to_blocks(plaintext, self.block_size)
cipher_blocks = [init_iv]
for plain_block in plain_blocks:
xor_block = fixedlen_xor(plain_block, cipher_blocks[-1])
cipher_blocks.append(self.aes_block_encryption(xor_block))
#Merge Cipher Blocks
return combind_blocks(cipher_blocks)
def cbc_decryption(self, ciphertext):
#First Block is the IV
cipher_blocks = to_blocks(ciphertext, self.block_size)
plain_blocks = []
for index in range(len(cipher_blocks)-1):
#print(cipher_block, len(cipher_block))
xor_block = self.aes_block_decryption(cipher_blocks[index+1])
#print("XOR: ", xor_block, "Last Block: ", cipher_blocks[index])
plain_blocks.append(fixedlen_xor(xor_block, cipher_blocks[index]))
#Merge plain_blocks but remove the first one that contains the IV
#print(plain_blocks)
return combind_blocks(plain_blocks)
def ecb_encryption(self, plaintext):
cipher_blocks = []
for plain_block in to_blocks(plaintext, self.block_size):
cipher_blocks.append(self.aes_block_encryption(plain_block))
return combind_blocks(cipher_blocks)
def ecb_decryption(self, ciphertext):
plain_blocks = []
for cipher_block in to_blocks(ciphertext, self.block_size):
plain_blocks.append(self.aes_block_decryption(cipher_block))
return combind_blocks(plain_blocks)
if __name__ == '__main__':
#AES 128 Key Test
plaintext = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]
key = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]
key2 = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]
key2a = [0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5, 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b]
key3 = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]
key3a = [0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4]
test = AES(key3)
#print(plaintext)
#mid = test._shift_rows(plaintext)
#print(mid)
#mid = test._reverse_shift_rows(mid)
#print(mid)
#print(plaintext)
#mid = test._sub_bytes(plaintext)
#print(mid)
#mid = test._reverse_sub_bytes(mid)
#print(mid)
#print(plaintext)
#mid = test._mix_columns(plaintext)
#print(mid)
#mid = test._reverse_mix_columns(mid)
#print(mid)
print(plaintext)
cypher = test.aes_block_encryption(plaintext)
print(binascii.hexlify(cypher))
plaintext2 = test.aes_block_decryption(cypher)
print(binascii.hexlify(plaintext2))