代码之家  ›  专栏  ›  技术社区  ›  MirageCommander

为什么我不能使用增量加密和解密照片文件?

  •  0
  • MirageCommander  · 技术社区  · 2 年前

    我制作了一个非常简单的加密和解密程序,通过将所有字节递增6来加密文件。然而,在测试中,只有文本文件起作用。如果我用它来加密和解密照片,操作系统将无法读取结果。

    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")
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Robert Vanden Eynde    2 年前

    此部件需要更改为 else :

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

    像这样:

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

    否则,如果 if 如果为true,则字节发生更改,第二个 如果 可能会运行,应用两倍的增量。

    解密也一样。