from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from base64 import b64encode, b64decode
# Function to correct base64 padding if needed
def correct_base64_padding(data):
missing_padding = len(data) % 4
if missing_padding:
data += '=' * (4 - missing_padding)
return data
# Simulated Oracle function that checks the padding
def oracle(iv, ciphertext):
key = bytes.fromhex("98313fb978e6ef49000000000000000000000000000000000000000000000000") # Fixed key for the simulation
cipher = AES.new(key, AES.MODE_CBC, iv)
try:
plaintext = cipher.decrypt(ciphertext)
# Check if the padding bytes are correct
padding_byte = plaintext[-1]
if isinstance(padding_byte, str): # Python 2 compatibility
padding_byte = ord(padding_byte)
padding = plaintext[-padding_byte:]
return all(p == padding_byte for p in padding)
except (ValueError, KeyError):
return False
# Padding Oracle Attack Implementation
def attack_16byte_iv(ciphertext):
block_size = 16
if len(ciphertext) % block_size != 0:
raise ValueError("Invalid ciphertext length")
plaintext = b""
blocks = [ciphertext[i:i + block_size] for i in range(0, len(ciphertext), block_size)]
previous_block = bytearray([0] * block_size)
# Generate a random IV
iv = get_random_bytes(16)
# Attack each block
for block in blocks:
recovered_block = bytearray([0] * block_size)
for i in range(1, block_size + 1):
for guess in range(256):
modified_iv = previous_block[:]
modified_iv[-i:] = bytearray([(guess ^ p) for p in recovered_block[-i+1:]])
modified_iv[-i] ^= i
if oracle(modified_iv, block): # Pass IV along with the ciphertext
recovered_block[-i] = guess ^ previous_block[-i]
break
plaintext += bytes(recovered_block)
previous_block = block
# Remove PKCS#7 padding
padding_length = plaintext[-1]
if isinstance(padding_length, str): # Python 2 compatibility
padding_length = ord(padding_length)
return plaintext[:-padding_length]
# Main execution flow
if __name__ == "__main__":
ciphertext_base64 = "DLZXaVkqeCT+FMFNgXHwOw5ES4CVncxS07JP9eTMng6kI6h5nsikvJSMqlDNF+yq"
ciphertext = b64decode(correct_base64_padding(ciphertext_base64))
plaintext = attack_16byte_iv(ciphertext)
print("nPlaintext:", plaintext.decode())
The IV is already 16 byte but it still shows this error “Incorrect IV length (it must be 16 bytes long)”
The IV is already 16 byte but it still shows this error “Incorrect IV length (it must be 16 bytes long)”
What code do.
Set up padding oracle attack on the IV 16 bye , and make it with functions like def 16attack and call the functions ,
Set up padding oracle attack on the 16 IV
->In the A we will have a fixed Key of 32 byte “98313fb978e6ef49000000000000000000000000000000000000000000000000”
On this file the attack is on the IV
Take a look on this
Wahab Kazim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.