0

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)



Itay
  • 3
  • 3
  • Ciphertext is not actually text, it is binary and you need to treat it that way. Where's that `crypt` call hiding? – Maarten Bodewes Apr 20 '20 at 23:34
  • I’m calling it with the following line: modify(r"C:\Users\XXXXX\Desktop\TEST.txt", encrypt_file) – Itay Apr 22 '20 at 17:06
  • You have a good sample here https://github.com/tedder/s3-client-side-encryption/blob/master/put.py (and get.py also has a good example about decryption, you just need to remove things related to AWS S3). – AsTeR Oct 28 '22 at 14:35

0 Answers0