0

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?

user2145312
  • 896
  • 3
  • 10
  • 33
  • 1
    You have completely altered the contents of the file, any image viewer you use to open the file is not looking for something that's been encrypted - how would the image viewer know the key to decrypt the image, or which method was used to encrypt it? – Kyle Pittman Oct 07 '15 at 18:46
  • I'm not looking for an image program to decrypt the file and display the original image. Im trying to understand how to encrypt the pixels and maintain the ability so that the image displayed is something like https://s.yimg.com/fz/api/res/1.2/NNhfHcYFTjDKSukxFSkvhQ--/YXBwaWQ9c3JjaGRkO2g9MjE2O3E9OTU7dz0xOTY-/http://upload.wikimedia.org/wikipedia/commons/a/a0/Tux_secure.jpg – user2145312 Oct 07 '15 at 18:49
  • 1
    Decode the image using an imaging library (ex. Pillow), encrypt the raw image data, and then re-encode the image. This will only work for lossless image formats; JPEG is unlikely to work. It's also fairly pointless. – Colonel Thirty Two Oct 07 '15 at 18:56

1 Answers1

0

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.

Community
  • 1
  • 1
Kyle Pittman
  • 2,858
  • 1
  • 30
  • 38