Python二进制文件会混淆一些文件

时间:2017-03-06 15:48:44

标签: python binary

我写了两个python脚本。其中一个将文件编码为二进制文件,将其存储为文本文件以供以后解密。另一个脚本可以将文本文件转换回可读信息,或者至少,这是我的目标。

脚本1(加密) (使用任何.png图像文件作为输入,任何.txt文件作为输出):

u_input = input("What file to encrypt?")
file_store = input("Where do you want to store the binary?")
character = "" #Blank for now
encrypted = "" #Blank for now, stores the bytes before they are written

with open(u_input, 'rb') as f:
    while True:
        c = f.read(1)
        if not c:
            f.close()
            break
        encrypted = encrypted + str(bin(ord(c))[2:].zfill(8))
print("")
print(encrypted) # This line is not necessary, but I have included it to show that the encryption works
print("")
with open(file_store, 'wb') as f:
    f.write(bytes(encrypted, 'UTF-8'))
    f.close()

据我所知,这适用于文本文件(.txt)

然后我有第二个脚本(解密文件) 使用以前创建的.txt文件作为源,将任何.png文件用作dest:

u_input =("Sourcefile:")
file_store = input("Decrypted output:")
character = ""
decoded_string = ""

with open(u_input, 'r' as f:
    while True:
        c = f.read(1)
        if not c:
            f.close()
            break
        character = character + c
        if len(character) % 8 == 0:
            decoded_string = decoded_string + chr(int(character, 2))
            character = ""

with open(file_store, 'wb') as f:
    f.write(bytes(decoded_string, 'UTF-8'))
    f.close()
    print("SUCCESS!")

部分有效。即它写入文件。但是,我无法打开或编辑它。当我将我的原始文件(img.png)与我的第二个文件(img2.png)进行比较时,我看到已经替换了字符或没有正确输入换行符。我无法在任何图像查看/编辑程序中查看该文件。我不明白为什么。

有人可以尝试解释并提供解决方案(尽管是部分的)吗?提前谢谢。

注意:我知道我对“加密”和“解密”的使用未必正确使用,但这是一个个人项目,因此对我来说无关紧要

1 个答案:

答案 0 :(得分:0)

您似乎正在使用Python 3,因为您在UTF-8调用上添加了bytes参数。这就是你的问题 - 输入应该被解码为一个字节字符串,但是你要将一个Unicode字符串组合在一起,而且转换不是1:1。它很容易解决。

decoded_string = b""
# ...
decoded_string = decoded_string + bytes([int(character, 2)])
# ...
f.write(decoded_string)

对于适用于Python 2和Python 3的版本,另一个小修改。这实际上对我来说在Python 3.5中测量速度更快,因此它应该是首选方法。

import struct
# ...
decoded_string = decoded_string + struct.pack('B', int(character, 2))