7.1 TAG! YOU’RE IT!

EXERCISE 7.1 TAG! YOU’RE IT!

Artificially “damage” different parts of an encrypted file including both the actual ciphertext and the salt, IV, or tag. Demonstrate that decrypting the file throws an exception.


If we change a single bit from the output of the encrypted file, we will get an InvalidTag exception.

Step 1: Let’s first encrypt some file.

import aes_gcm

aes_gcm.encrypt_file(
    plainpath="top_secret.bin",
    cipherpath="top_secret_encrypted.bin",
    password=b"secured123",
)

Step 2: Change a single byte from the encrypted file

with open("top_secret_encrypted.bin", 'rb') as src: 
    with open("top_secret_encrypted2.bin", 'wb') as dest:
        data = src.read()
        first_byte = ((data[0] + 1) % 256).to_bytes(length=1, byteorder='little')
        dest.write(first_byte + data[1:]) 

Step 3: Try to decrypt the tampered file

import traceback 

try: 
    aes_gcm.decrypt_file(
        cipherpath="top_secret_encrypted2.bin",
        plainpath="top_secret2.bin",
        password=b"secured123",
    )
except Exception as e:
    traceback.print_exc() 
Traceback (most recent call last):
  File "/tmp/ipykernel_119154/1648948399.py", line 4, in <module>
    aes_gcm.decrypt_file(
  File "/home/data53/code/repos/practical_cryptography_in_python_answers/Ch7_Authenticated_Encryption_and_Kerberos/aes_gcm.py", line 94, in decrypt_file
    decryptor.finalize()
  File "/home/data53/code/repos/practical_cryptography_in_python_answers/env/lib/python3.10/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 228, in finalize
    data = self._ctx.finalize()
  File "/home/data53/code/repos/practical_cryptography_in_python_answers/env/lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/ciphers.py", line 200, in finalize
    raise InvalidTag
cryptography.exceptions.InvalidTag