def encrypt(self, plaintext): ptBlocks = self.getBlocks(plaintext) ciphertext = b'' prev = self.IV for block in ptBlocks: toEnc = xor(prev, block) cipherBlock = self.ECB.encrypt(bytes(toEnc)) prev = cipherBlock #print(cipherBlock) ciphertext += cipherBlock return ciphertext
def decrypt(self, ciphertext): #Split the ciphertext into blocks ctBlocks = self.getBlocks(ciphertext) plaintext = b'' prev = self.IV for block in ctBlocks: #Decrypt the ciphertext block and xor it with the IV/Previous block plainBlock = bytes(xor(prev, self.ECB.decrypt(block))) prev = block plaintext += plainBlock return plaintext
def main(): ans = "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272" ans += "a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f" ans = bytearray.fromhex(ans) inputStr = "Burning 'em, if you ain't quick and nimble\n" inputStr += "I go crazy when I hear a cymbal" key = "ICE" inputArr = bytearray(inputStr.encode()) keyArr = bytearray(key.encode()) res = xor(inputArr,keyArr) print(binascii.hexlify(res)) validate(res, ans)
def main(): ans = "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272" ans += "a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f" ans = bytearray.fromhex(ans) inputStr = "Burning 'em, if you ain't quick and nimble\n" inputStr += "I go crazy when I hear a cymbal" key = "ICE" inputArr = bytearray(inputStr.encode()) keyArr = bytearray(key.encode()) res = xor(inputArr, keyArr) print(binascii.hexlify(res)) validate(res, ans)
def main(): inputFile = "assets/Set1/inputC6.txt" inputStr = '' newHam = 0 bestHam = 10000 keyLen = 0 key = None res = None #Read in the entire file and concatenate it to a string. for line in open(inputFile,"r"): inputStr += line.rstrip() #Decode the input from base 64 and convert it to a byte string. decodedStr = bytearray(base64.b64decode(inputStr)) #print(inputStr) #print(base64.b64decode(inputStr)) for i in range(1,40): newHam = avgHamming(decodedStr,i, 10) / i #print(i,"hamming dist",newHam) if(newHam < bestHam): bestHam = newHam keyLen = i #Create the array that will store the key key = bytearray(keyLen) for i in range(0,keyLen): encChunk = everyNth(decodedStr,keyLen, i) (k,d,r) = xorBruteForce1(encChunk) key[i] = k print("Key:", key.decode()) print("\n\nDeciphered text:") res = xor(decodedStr,key) #print(res) print(res.decode("ascii"))
def calcHamming(arr1, arr2): numBits = 0 resArr = xor(arr1,arr2) for j in range(0,len(arr1)): numBits += bin(resArr[j]).count('1') return numBits