| 140 |
Kevin |
1 |
import math
|
|
|
2 |
|
|
|
3 |
substitution_map = {14:0,4:1,13:2,1:3,2:4,15:5,11:6,8:7,3:8,10:9,6:10,12:11,5:12,9:13,0:14,7:15}
|
|
|
4 |
|
|
|
5 |
key = [3,10,9,4,13,6,3,15] # Key
|
|
|
6 |
key_length = len(key) * 4 # Calculate length of the key in bits
|
|
|
7 |
bytes_per_key = key_length / 8 # Calculate the number of bytes for each round key (4 for a 32-bit key)
|
|
|
8 |
rounds = int(math.log(key_length,2)) # Calculate the number of rounds (5 for a 32-bit key)
|
|
|
9 |
|
|
|
10 |
ciphertext = [6,4,15,13]
|
|
|
11 |
|
|
|
12 |
def get_key(key, round):
|
|
|
13 |
'''Returns the round key for the specified key.
|
|
|
14 |
The round key is bytes_per_key bytes starting at the specified offset determined by round.'''
|
|
|
15 |
round -= 1
|
|
|
16 |
ret = []
|
|
|
17 |
for index in range(bytes_per_key):
|
|
|
18 |
ret.append(key[index + round])
|
|
|
19 |
return ret
|
|
|
20 |
|
|
|
21 |
def xor_array(array, key):
|
|
|
22 |
'''Xor the two arrays and returns the result.'''
|
|
|
23 |
ret = []
|
|
|
24 |
for index in range(len(array)):
|
|
|
25 |
ret.append(array[index] ^ key[index])
|
|
|
26 |
return ret
|
|
|
27 |
|
|
|
28 |
def sub_array(array):
|
|
|
29 |
'''Runs the given array through the substitution map and returns the result.'''
|
|
|
30 |
ret = []
|
|
|
31 |
for index in range(len(array)):
|
|
|
32 |
ret.append(substitution_map[array[index]])
|
|
|
33 |
return ret
|
|
|
34 |
|
|
|
35 |
def perm_array(array):
|
|
|
36 |
'''Permutes the given array and returns the results.'''
|
|
|
37 |
ret = []
|
|
|
38 |
for index in range(bytes_per_key-1,-1,-1):
|
|
|
39 |
value = 0
|
|
|
40 |
for entry in array:
|
|
|
41 |
value <<= 1
|
|
|
42 |
value |= (entry >> index) & 1
|
|
|
43 |
ret.append(value)
|
|
|
44 |
return ret
|
|
|
45 |
|
|
|
46 |
if __name__ == '__main__':
|
|
|
47 |
working_array = ciphertext # Initial array is the ciphertext
|
|
|
48 |
print "Ciphertext:\t\t\t\t", ciphertext
|
|
|
49 |
print
|
|
|
50 |
|
|
|
51 |
# Print out the results for each step as it is calculated
|
|
|
52 |
for round in range(rounds,1,-1):
|
|
|
53 |
print "Round {0} Key:\t\t\t".format(round), get_key(key, round)
|
|
|
54 |
working_array = xor_array(working_array, get_key(key, round))
|
|
|
55 |
print "Round {0} U (xor'ed):\t\t".format(round),working_array
|
|
|
56 |
if round != rounds:
|
|
|
57 |
working_array = perm_array(working_array)
|
|
|
58 |
print "Round {0} W (perm'ed):\t".format(round),working_array
|
|
|
59 |
working_array = sub_array(working_array)
|
|
|
60 |
print "Round {0} V (sub'ed):\t\t".format(round),working_array
|
|
|
61 |
print
|
|
|
62 |
|
|
|
63 |
# Print out the final round key and xor'ed result (plaintext)
|
|
|
64 |
print "Round 1 Key:\t\t\t",get_key(key, 1)
|
|
|
65 |
working_array = xor_array(working_array, get_key(key, 1))
|
|
|
66 |
print("Plaintext (xor'ed):\t\t"), working_array
|