Skip to content

CTR

Counter Mode (CTR)

This is GCM mode but without the GHASH MAC.

Attacks

CTR Bit flipping

from cryptopals_lib import *
import os
from aes_lib import AES

if __name__ == '__main__':
	key =       [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]
	aes_obj = AES(key)
	plaintext = b"comment=\"test\";admin=false;username=test"
	nonce = os.urandom(16)
	print(f"Unencrypted: {plaintext}")
	#Unencrypted: b'comment="test";admin=false;username=test'


	encrypted = aes_obj.ctr_encryption(nonce, plaintext)
	print(f"Encrypted: {encrypted}")
	#Encrypted: b'y\x8f%\xa1Wo\xc3\x01\xec\xc6\xf1\t6?\xdfT\xcc\x99\xfaw\x84\x04\x85J\x0c\x10a\xfa!\xbf5!\x13\x04\x15\x08\xf9i8\x81'


	### Remove the admin=false from ciphertext
	xor_data = b"\x00" * len("comment=\"test\";") + b"admin=false" + b"\x00" * len("e;username=test")
	removed_data = shortest_xor(xor_data, encrypted)
	temp_unencrypted =  aes_obj.ctr_decryption(nonce, removed_data)
	print(f"Removed Tag Encrypted:  {removed_data}")
	#Removed Tag Encrypted:  b'y\x8f%\xa1Wo\xc3\x01\xec\xc6\xf1\t6?\xdf5\xa8\xf4\x93\x19\xb9b\xe4&\x7fua\xfa!\xbf5!\x13\x04\x15\x08\xf9i8\x81'

	print(f"Removed Tag unencrypted {temp_unencrypted}")
	#Removed Tag unencrypted b'comment="test";\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00;username=test'

	### Add the admin=true; to the ciphertext
	xor_data = b"\x00" * len("comment=\"test\";") + b"admin=true;" + b"\x00" * len("e;username=test")
	added_data = shortest_xor(xor_data, removed_data)
	temp_unencrypted =  aes_obj.ctr_decryption(nonce, added_data)
	print(f"Added Tag Encrypted:  {added_data}")
	#Added Tag Encrypted:  b'y\x8f%\xa1Wo\xc3\x01\xec\xc6\xf1\t6?\xdfT\xcc\x99\xfaw\x84\x16\x96S\x1aNa\xfa!\xbf5!\x13\x04\x15\x08\xf9i8\x81'

	print(f"Added Tag unencrypted {temp_unencrypted}")
	#Added Tag unencrypted b'comment="test";admin=true;;username=test'