def bin_to_ascii(ba): ba = bytearray(ba) data = '' for i in range(len(ba)): temp = hex(ba[i]) data = data + temp return data
def CBC(data, lastCipher): # pad temp = data + ('0' * (32 - len(data))) temp = int(lastCipher, 16) ^ int(temp, 16) temp = hex(temp) # fix length temp = ('0' * (32 - len(temp))) + temp return temp
def core(val): global roundNum RCon = modz(1 << roundNum) val = val[2:] + val[:2] ret = sub(val) swap = hex(int(ret[:2], 16) ^ RCon) ret = swap + ret[2:] roundNum = roundNum + 1 return ret
def inverse(x, b=aes_b): ix = int(x, 16) if (ix > b): ix = modz(ix, b) bx = bin(ix) q_list = [] tempdiv = b tempq, tempr = divide(ix, tempdiv) while tempr != 0: q_list.append(tempq) tempdiv = ix ix = tempr tempq, tempr = divide(ix, tempdiv) ret = hex(EEA(q_list)) return ret
def expand(key, encrypt=True): try: test = int(key, 16) except: print("Invalid input type. Please enter hex value.") return 1 keylen = len(key) * 4 if (keylen != 128) and (keylen != 192) and (keylen != 256): print("Invalid key length. Please use 128, 192, or 256 bit key.") return 2 numRounds = 10 + int((keylen - 128) / 32) # 16 byte keys, 1 byte = 2 chars expKeyLen = (numRounds + 1) * 16 * 2 expKey = key global roundNum roundNum = 0 # max value of j from key expansion loop iterMax = 4 + (numRounds - 10) while len(expKey) < expKeyLen: # 4,6,8 for 128, 192, 256 bit keys for i in range (iterMax): temp1 = expKey[len(expKey) - 8:] if i == 0: temp1 = core(temp1) if (i == 4) and (iterMax == 8): temp1 = sub(temp1) temp2 = expKey[len(expKey) - (8 * iterMax):] temp2 = temp2[:8] xor = hex(int(temp1, 16) ^ int(temp2, 16)) xor = '0' * (8 - len(xor)) + xor expKey = expKey + xor expKey = expKey[:expKeyLen] roundKeys = [] for i in range(numRounds + 1): roundKeys.append(expKey[i*32:(i+1)*32]) if not encrypt: roundKeys.reverse() return roundKeys
def mix_cols(data, encrypt=True): multMat = mixMat if encrypt else invMat # convert string to matrix tmpMat = strToMat(data) ret = [] # each column of data for i in range(4): ret.append([]) # each row of mult matrix for j in range(4): tmp = 0 # each item in the row for k in range(4): tmp = tmp ^ int(multiply(multMat[j][k], tmpMat[k][i]), 16) tmp = modz(tmp) # convert to string tmp = hex(tmp) ret[i].append(tmp) # convert matrix back to string tmp = [] for i in range(4): tmp.append(''.join(ret[i])) ret = ''.join(tmp) return ret
def EEA(q_list): k_list = [0b0, 0b1] for i in range(len(q_list)): k_list.append(k_list[i] ^ int(multiply(hex(k_list[i + 1]), hex(q_list[i])), 16)) return k_list[len(k_list) - 1]