Path: blob/master/Block-Cipher/CBC-IV-Detection/example.py
871 views
from Crypto.Cipher import AES1from os import urandom23key = urandom(16)4iv = urandom(16)56def padding(plaintext, blocksize):7padlen = blocksize - (len(plaintext) % blocksize)8pt_hex = plaintext.encode("hex") + padlen*(hex(padlen)[2:].zfill(2))9return pt_hex.decode("hex")1011def CBC_encrypt(plaintext):12plaintext = padding(plaintext, 16)13obj1 = AES.new(key, AES.MODE_CBC, iv)14return obj1.encrypt(plaintext)1516def CBC_decrypt(ciphertext):17obj2 = AES.new(key, AES.MODE_CBC, iv)18plaintext = obj2.decrypt(ciphertext)19return plaintext2021# Assuming the above code is running on a server and we only have access to its encryption and decryption oracle22# We can do the following, as an attacker to get the value of iv23#----------------------------------------------------------------------------------------------------------------------------------24# The following is what an attacker will do to implement the exploit2526plaintext = "Crypton is a repository of a compilation of all the popular attacks on encryption systems and digital signatures"27plaintext = padding(plaintext, 16) # Assuming that the attacker knows blocksize28ciphertext = CBC_encrypt(plaintext)2930# For the exploit we need atleast three blocks of ciphertext31ciphertext = ciphertext[:16] + "\x00"*16 + ciphertext[:16]32pt = CBC_decrypt(ciphertext)33possible_iv = ""34for i in range(16):35possible_iv += chr(ord(pt[i]) ^ ord(pt[32+i]))36print possible_iv == iv3738if possible_iv == iv:39print "[*] Exploit working. The value of iv in hex is: ", possible_iv.encode("hex")40else:41print "[*] Exploit failed!"424344