I'm struggling to find the issue within the code:
I've txt file on my desktop that i want to encrypt, then decrypt. I'm using AES CBC as my encryption method.
Assume the file contain the following string:
bla bla top secret!!
I'm able to encrypt it successfully with the following line: modify(r"C:\Users\XXXXX\Desktop\TEST.txt", encrypt_file)
output: W¢ìPY#Šÿb[l®«fì]ßQzýµá˺cØäûE
Then I'm trying to decrypt it with the following line modify(r"C:\Users\XXXXX\Desktop\TEST.txt", decrypt_file)
I'm getting the following exception: ValueError: Padding is incorrect.
If I remove the unpad function i can see the text is partical unencrypted as follow: bla bla top secrv€\Èu¢Þ@xH‹AÄ
I can't find whats wrong here.
Any help will be appreciated.
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
HARD_CODED_KEY = b"SOME KEY"
iv = b'1234567812345678'
def encrypt_file(file, key, blocksize=16):
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(file, blocksize))
return ciphertext
def decrypt_file(file, key, blocksize=16):
cipher = AES.new(key, AES.MODE_CBC, iv)
cleartext = unpad(cipher.decrypt(file), blocksize)
return cleartext
def modify(file, crypt, blocksize=16):
with open(file, "r+b") as f:
plaintext = f.read(blocksize)
while plaintext:
ciphertext = crypt(plaintext, HARD_CODED_KEY, blocksize)
f.seek(-len(plaintext), 1) # go back to the same point before the read
f.write(ciphertext)
plaintext = f.read(blocksize)