def get_replacement_byte(orig, new): h1 = str(binascii.hexlify(my_encode(orig)))[2:-1] h2 = str(binascii.hexlify(my_encode("x")))[2:-1] h3 = str(binascii.hexlify(my_encode(new)))[2:-1] temp = binary_xor(h1, h2) r_byte = binary_xor(bin2hex(temp), h3) return r_byte
def decrypt_cbc(c, k, iv, padding): # make list of blocks blocks = [] for i in range(0, int(len(c)/16)): b = c[i * 16:i * 16 + 16] blocks.append(b) # decrypt and xor to get plaintext h1 = binascii.hexlify(iv) plain_blocks = [] for b in blocks: undo_aes = my_encode(decrypt_ecb(b, k)) h2 = binascii.hexlify(undo_aes) x = binary_xor(h1.decode('latin1'), h2.decode('latin1')) h1 = binascii.hexlify(b) # update h1 for next iteration x = hex(int(x, 2))[2:].zfill(32) plain_block = str(binascii.unhexlify(x), 'latin1') plain_blocks.append(plain_block) plaintext = ''.join(plain_blocks) if padding: return chop(plaintext) else: return plaintext
def encrypt_cbc(p, k, iv): p = pkcs7_pad(p.decode('latin1'), 128) # make list of blocks blocks = [] for i in range(0, int(len(p) / 16)): b = p[i * 16:i * 16 + 16] blocks.append(b) # xor and encrypt to get ciphertext h1 = binascii.hexlify(iv) c_text = [] for b in blocks: h2 = binascii.hexlify(b) x = binary_xor(h1.decode('latin1'), h2.decode('latin1')) x = hex(int(x, 2))[2:].zfill(32) do_aes = encrypt_ecb(binascii.unhexlify(x), k, False) h1 = binascii.hexlify(do_aes) # update h1 for next iteration c_text.append(str(do_aes, 'latin1')) return ''.join(c_text)
def decrypt_cbc(c, k, iv): # make list of blocks blocks = [] for i in range(0, int(len(c) / 16)): b = c[i * 16:i * 16 + 16] blocks.append(b) # decrypt and xor to get plaintext h1 = binascii.hexlify(iv) plain_blocks = [] for b in blocks: undo_aes = my_encode(decrypt_ecb(b, k)) h2 = binascii.hexlify(undo_aes) x = binary_xor(h1.decode('latin1'), h2.decode('latin1')) h1 = binascii.hexlify(b) # update h1 for next iteration x = hex(int(x, 2))[2:].zfill(32) plain_block = str(binascii.unhexlify(x), 'latin1') plain_blocks.append(plain_block) plaintext = ''.join(plain_blocks) # chop off any pkcs7 padding b_array = bytearray(str.encode(plaintext)) last_byte = b_array[-1] if last_byte <= 16: padding_found = True for i in range(1, last_byte + 1): if b_array[0 - i] != i: padding_found = False break if padding_found: for i in range(0, last_byte): b_array.pop() return bytes(b_array).decode('ascii')
def three_xor(a1, a2, a3): temp = binary_xor(a1, a2) return binary_xor(bin2hex(temp), a3)