icey
icey

Reputation: 11

Python AES Encryption. First 16 characters of every file but one is replaced with encoded bytes

The basis of this task I am trying to do is the following.

For a given directory (in this case I am using "/playground") use AES encryption to encrypt all .txt files. These files are then able to be decrypted by running two seperate python scripts (one to create a key in a required format and the other to do the decryption).

The issue I am facing is that when I have one file it seems to encrypt and decrypt it just fine. When I have multiple files however, the first 16 bytes of every file are corrupted except for one file. I believe it may be an issue with the padding of files and the IV but I am very new to this and cannot work it out. The structure of the directory and files can be seen below.

|
|-- encrypt.py
|-- recover_key.py
|-- decrypt.py
|-- pem_private_key.pem
|-- playground
| |-- file1.txt
| |-- file2.txt
| |-- file3.txt
|

Upvotes: 1

Views: 991

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94038

What is happening is that you use the same cipher object for encrypting the different files. You should not do that; you should create a new cipher object for each encryption and create a fresh IV. The IV is usually prefixed to the ciphertext for CBC mode.

In CBC the previous ciphertext block is used as "vector" to encrypt the next block. If you keep encrypting with the same cipher then the plaintext of a starting block of a file is XOR-ed with the ciphertext of the previous file: the last ciphertext block of the last file acts as IV. If you don't decrypt in exactly the same order then decryption will fail for the first block of 16 bytes. Of course you want to make sure that the decryption of files doesn't depend on any other files though - adjusting the decryption order is not a good solution.

Upvotes: 1

Related Questions