Blame | Last modification | View Log | Download | RSS feed
import mathsubstitution_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] # Keykey_length = len(key) * 4 # Calculate length of the key in bitsbytes_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 -= 1ret = []for index in range(bytes_per_key):ret.append(key[index + round])return retdef 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 retdef 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 retdef perm_array(array):'''Permutes the given array and returns the results.'''ret = []for index in range(bytes_per_key-1,-1,-1):value = 0for entry in array:value <<= 1value |= (entry >> index) & 1ret.append(value)return retif __name__ == '__main__':working_array = ciphertext # Initial array is the ciphertextprint "Ciphertext:\t\t\t\t", ciphertext# Print out the results for each step as it is calculatedfor 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_arrayif round != rounds:working_array = perm_array(working_array)print "Round {0} W (perm'ed):\t".format(round),working_arrayworking_array = sub_array(working_array)print "Round {0} V (sub'ed):\t\t".format(round),working_array# 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