相关疑难解决方法(0)

用Python读写二进制文件

以下代码似乎没有正确读/写二进制形式.它应该读取一个二进制文件,逐位XOR数据并将其写回文件.没有任何语法错误,但数据无法验证,我已通过其他工具测试源数据以确认xor密钥.

更新:根据评论中的反馈,这很可能是由于我正在测试的系统的字节序.

xortools.py:

def four_byte_xor(buf, key):
    out = ''
    for i in range(0,len(buf)/4):
        c = struct.unpack("=I", buf[(i*4):(i*4)+4])[0]
        c ^= key
        out += struct.pack("=I", c)
    return out
Run Code Online (Sandbox Code Playgroud)

调用xortools.py:

from xortools import four_byte_xor
in_buf = open('infile.bin','rb').read()
out_buf = open('outfile.bin','wb')
out_buf.write(four_byte_xor(in_buf, 0x01010101))
out_buf.close()
Run Code Online (Sandbox Code Playgroud)

看来我需要读取每个答案的字节数.由于上面的函数操作多个字节,上面的函数如何合并到下面?或者没关系?我需要使用struct吗?

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        byte = f.read(1)
Run Code Online (Sandbox Code Playgroud)

例如,以下文件有4个重复字节,01020304:

在XOR之前

使用01020304的密钥对数据进行异或操作,该密钥将原始字节归零:

在XOR之后

这是对原始函数的尝试,在这种情况下,05010501的结果是不正确的:

不正确的XOR尝试

python

8
推荐指数
1
解决办法
3万
查看次数

标签 统计

python ×1