Home > OS >  Why couldn't I encrypt and decrypt a photo file using increments?
Why couldn't I encrypt and decrypt a photo file using increments?

Time:05-16

I made a very simple encryption and decryption program to encrypt files by incrementing all bytes by 6. However, in testing, only text files work. If I use it to encrypt and decrypt photos, the result is not readable by the OS.

Code in Python:

import os.path


class fileEncryptor:

    @staticmethod
    def encrypt(fileLocation, destination):
        if os.path.exists(fileLocation):
            file = open(fileLocation, "rb")
            fileContents = file.read()  # fileContents is a byte string
            file.close()

            btAr = bytearray(fileContents)  # Byte string needs to be changed to byte array to manipulate


            length = len(btAr)
            n = 0
            while n < length:
                increment = 6
                if btAr[n] <= 249:
                    btAr[n] = btAr[n]   increment
                if 249 < btAr[n] <= 255:
                    btAr[n] = btAr[n] - 250
                n = n   1

            encryptedFile = open(destination, "wb")
            encryptedFile.write(btAr)
            encryptedFile.close()
        else:
            print("File does not exist")

    @staticmethod
    def decrypt(fileLocation, destination):
        if os.path.exists(fileLocation):
            file = open(fileLocation, "rb")
            fileContents = file.read()
            file.close()

            btAr = bytearray(fileContents)

            length = len(btAr)
            n = 0
            while n < length:
                increment = 6
                if 5 < btAr[n] <= 255:
                    btAr[n] = btAr[n] - increment
                if btAr[n] <= 5:
                    btAr[n] = btAr[n]   250
                n = n   1

            decryptedFile = open(destination, "wb")
            decryptedFile.write(btAr)
            decryptedFile.close()
        else:
            print("File does not exist")


if __name__ == "__main__":
    fileEncryptor.encrypt("D:\Python Projects\DesignerProject\ic.ico", "D:\Python Projects\DesignerProject\output\ic.ico")
    fileEncryptor.decrypt("D:\Python Projects\DesignerProject\output\ic.ico", "D:\Python Projects\DesignerProject\output\i.ico")

CodePudding user response:

This part needs to be changed to a else :

if btAr[n] <= 249:
    btAr[n] = btAr[n]   increment
if 249 < btAr[n] <= 255:
    btAr[n] = btAr[n] - 250

Like this :

if btAr[n] <= 249:
    btAr[n] = btAr[n]   increment
else:
    btAr[n] = btAr[n] - 250

Otherwise, if the first if is true, the byte is changed and the second if might be runned, applying twice the increment.

Same for the decryption.

  • Related