Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/Crypton
Path: blob/master/Block-Cipher/CBC-IV-Detection/example.py
871 views
1
from Crypto.Cipher import AES
2
from os import urandom
3
4
key = urandom(16)
5
iv = urandom(16)
6
7
def padding(plaintext, blocksize):
8
padlen = blocksize - (len(plaintext) % blocksize)
9
pt_hex = plaintext.encode("hex") + padlen*(hex(padlen)[2:].zfill(2))
10
return pt_hex.decode("hex")
11
12
def CBC_encrypt(plaintext):
13
plaintext = padding(plaintext, 16)
14
obj1 = AES.new(key, AES.MODE_CBC, iv)
15
return obj1.encrypt(plaintext)
16
17
def CBC_decrypt(ciphertext):
18
obj2 = AES.new(key, AES.MODE_CBC, iv)
19
plaintext = obj2.decrypt(ciphertext)
20
return plaintext
21
22
# Assuming the above code is running on a server and we only have access to its encryption and decryption oracle
23
# We can do the following, as an attacker to get the value of iv
24
#----------------------------------------------------------------------------------------------------------------------------------
25
# The following is what an attacker will do to implement the exploit
26
27
plaintext = "Crypton is a repository of a compilation of all the popular attacks on encryption systems and digital signatures"
28
plaintext = padding(plaintext, 16) # Assuming that the attacker knows blocksize
29
ciphertext = CBC_encrypt(plaintext)
30
31
# For the exploit we need atleast three blocks of ciphertext
32
ciphertext = ciphertext[:16] + "\x00"*16 + ciphertext[:16]
33
pt = CBC_decrypt(ciphertext)
34
possible_iv = ""
35
for i in range(16):
36
possible_iv += chr(ord(pt[i]) ^ ord(pt[32+i]))
37
print possible_iv == iv
38
39
if possible_iv == iv:
40
print "[*] Exploit working. The value of iv in hex is: ", possible_iv.encode("hex")
41
else:
42
print "[*] Exploit failed!"
43
44