python Pycrypto how can I encrypt files and not corrupt them

1.1k views Asked by At

I've been dealing with this problem for quite some time now.

When I try to encrypt a file with PyCrypto. I can encrypt and decrypt it (only works with images so far). The problem is that the image becomes corrupted when I encrypt it and try to open it. How can I fix it so I can still run the program or see the image when it's been encrypted?

Here is the encryption code:

from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import os

def Encryption(Key, filename):
    chunksize = 64*1024
    outputFile = "[CryptoReady]"+filename
    filesize = str(os.path.getsize(filename)).zfill(16)
    IV = Random.new().read(16)

encryptor = AES.new(Key, AES.MODE_CBC, IV)

with open(filename, 'rb') as infile:
    with open(outputFile, 'wb') as outfile:
        outfile.write(filesize.encode('utf-8'))
        outfile.write(IV)

        while True:
            chunk = infile.read(chunksize)

            if len(chunk) == 0:
                break
            elif len(chunk) % 16 != 0:
                chunk += b'}' * (16 - (len(chunk) % 16))

            outfile.write(encryptor.encrypt(chunk))
1

There are 1 answers

0
summerNight On

When you encrypt a file, its contents are run through an algorithm and the contents are changed. If your file is a JPEG, its headers are also changed causing it to look-like corrupt if you try to open it using file viewers.

However, what's happening behind the scenes is they have just been transformed from X to let's say Y. To bring it back and have your image viewer easily open it, you will need to run the file thorough a decryption algorithm using the appropriate keys. That way your Y type will be transformed back exactly to X type and you will be able to read it.