简体   繁体   中英

maintain filetype when encrypting a file

I have written an AES cipher in python to help me understand its implementation in software.

I am reading the file contents into a bytearray using:

with open(self.plaintext_file_path, 'rb') as f:
    self.plaintext_data = bytearray(f.read())

the plaintext_data then gets run through the cipher and outputs ciphertext_data. It's then saved back to a file after the bytes have been encrypted using:

with open(fname, 'wb') as f:
    f.write(self.ciphertext_data)

the file extension (for example .jpg) is maintained in the filename that I am using to save the data though the resulting file will not open as an image. why?

If you'd like the image to be readable by an image program, you'll need to look up the specifications for JPEG or your image format of choice.

See this related question or google the JPEG file format & magic number specifications.

Once you have made the boilerplate data for the smallest possible JPEG file, then you can inject your encrypted data in the appropriate location in the file and write it back to the disk.

You may want to create a function to strip out the JPEG boilerplate from the original image file as well, so that you're only encrypting the actual image data and not encrypting the boilerplate bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM