import aes_gcm
aes_gcm.encrypt_file(="top_secret.bin",
plainpath="top_secret_encrypted.bin",
cipherpath=b"secured123",
password )
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.
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:
= src.read()
data = ((data[0] + 1) % 256).to_bytes(length=1, byteorder='little')
first_byte + data[1:]) dest.write(first_byte
Step 3: Try to decrypt the tampered file
import traceback
try:
aes_gcm.decrypt_file(="top_secret_encrypted2.bin",
cipherpath="top_secret2.bin",
plainpath=b"secured123",
password
)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