Subversion Repositories Code-Repo

Compare Revisions

Ignore whitespace Rev 139 → Rev 140

/Classwork/MATH4175 - Cryptography 1/SPN Decode.py
0,0 → 1,66
import math
 
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}
 
key = [3,10,9,4,13,6,3,15] # Key
key_length = len(key) * 4 # Calculate length of the key in bits
bytes_per_key = key_length / 8 # Calculate the number of bytes for each round key (4 for a 32-bit key)
rounds = int(math.log(key_length,2)) # Calculate the number of rounds (5 for a 32-bit key)
 
ciphertext = [6,4,15,13]
 
def get_key(key, round):
'''Returns the round key for the specified key.
The round key is bytes_per_key bytes starting at the specified offset determined by round.'''
round -= 1
ret = []
for index in range(bytes_per_key):
ret.append(key[index + round])
return ret
 
def xor_array(array, key):
'''Xor the two arrays and returns the result.'''
ret = []
for index in range(len(array)):
ret.append(array[index] ^ key[index])
return ret
 
def sub_array(array):
'''Runs the given array through the substitution map and returns the result.'''
ret = []
for index in range(len(array)):
ret.append(substitution_map[array[index]])
return ret
 
def perm_array(array):
'''Permutes the given array and returns the results.'''
ret = []
for index in range(bytes_per_key-1,-1,-1):
value = 0
for entry in array:
value <<= 1
value |= (entry >> index) & 1
ret.append(value)
return ret
 
if __name__ == '__main__':
working_array = ciphertext # Initial array is the ciphertext
print "Ciphertext:\t\t\t\t", ciphertext
print
 
# Print out the results for each step as it is calculated
for round in range(rounds,1,-1):
print "Round {0} Key:\t\t\t".format(round), get_key(key, round)
working_array = xor_array(working_array, get_key(key, round))
print "Round {0} U (xor'ed):\t\t".format(round),working_array
if round != rounds:
working_array = perm_array(working_array)
print "Round {0} W (perm'ed):\t".format(round),working_array
working_array = sub_array(working_array)
print "Round {0} V (sub'ed):\t\t".format(round),working_array
print
 
# Print out the final round key and xor'ed result (plaintext)
print "Round 1 Key:\t\t\t",get_key(key, 1)
working_array = xor_array(working_array, get_key(key, 1))
print("Plaintext (xor'ed):\t\t"), working_array