首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我不能用增量加密和解密照片文件?

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

Stack Overflow用户
提问于 2022-05-15 21:51:52
回答 1查看 31关注 0票数 0

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

Python中的代码:

代码语言:javascript
复制
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")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-15 22:14:50

此部分需要更改为else

代码语言:javascript
复制
if btAr[n] <= 249:
    btAr[n] = btAr[n] + increment
if 249 < btAr[n] <= 255:
    btAr[n] = btAr[n] - 250

就像这样:

代码语言:javascript
复制
if btAr[n] <= 249:
    btAr[n] = btAr[n] + increment
else:
    btAr[n] = btAr[n] - 250

否则,如果第一个if为真,则更改字节并运行第二个if,应用增量的两倍。

解密也一样。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72252454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档