[Answered ]-Django Python: How do I decrypt an AES-CTR mode encrypted file in the Python shell?

1👍

During encryption, IV and ciphertext are concatenated: IV || ciphertext. During decryption, a random IV is used, which is wrong. Instead, the IV of the encryption must be applied. For this, IV and ciphertext have to be separated.
In addition, the update() and finalize() methods must be called, which perform the actual decryption.

The following code essentially matches your code, extended by the missing parts:

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

# Read ciphertext
openfile = open("encrypted.txt", 'rb')
read = openfile.read()
openfile.close()

# Separate IV and ciphertext; decrypt
iv = read[:16]
ciphertext = read[16:]
key = b'\x1a>\xf8\xcd\xe2\x8e_~V\x14\x98\xc2\x1f\xf9\xea\xf8\xd7c\xb3`!d\xd4\xe3+\xf7Q\x83\xb5~\x8f\xdd'
cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
decryptor = cipher.decryptor()
decrypted = decryptor.update(ciphertext) + decryptor.finalize()

# Store decrypted data
savefile = open("decrypted.txt", "wb")
savefile.write(decrypted)
savefile.close()

This code successfully decrypts the ciphertext in the linked file (using the posted key).

👤Topaco

Leave a comment