以下函数接受 key
的二进制 4 字节 key 。 buf
是二进制输入,与 4 字节 key 进行异或运算。
def four_byte_xor(buf, key):
#key = struct.pack(b">I", key) # removed for binary processing
buf = bytearray(buf)
for offset in range(0, len(buf), 4):
for i, byte in enumerate(key):
buf[offset + i] = chr(buf[offset + i] ^ ord(byte))
return str(buf)
我从 four_byte_xor()
中删除了 key = struct.pack(b">I", key)
,以便通过 str(p .payload.payload.payload)[:4]
用于 key
。如果长度以 4 字节结尾,则效果很好,否则会引发以下错误(请参阅下面的测试)。
以下是一些测试,其中包含输入异或结果为 00 的 key ,第一个测试成功:
'ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD'
'ABCD'
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
'ABCD'
第二次测试未成功并以 A 或 1 个额外字节结束:
'ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDA'
'ABCD'
Traceback (most recent call last):
File "./decode.py", line 36, in <module>
process_packets()
File "./decode.py", line 34, in process_packets
out_buf.write(bin_four_byte_xor(pkt_payload, pkt_offset))
File "./decode.py", line 22, in bin_four_byte_xor
buf[offset + i] = chr(buf[offset + i] ^ ord(byte))
IndexError: bytearray index out of range
可以修改four_byte_xor()
以接受不同的buf
长度吗?
最佳答案
当然,您可以修改该函数以接受不同的 key 长度。例如,类似
def many_byte_xor(buf, key):
buf = bytearray(buf)
for i, bufbyte in enumerate(buf):
buf[i] = chr(bufbyte ^ ord(key[i % len(key)]))
return str(buf)
循环遍历 key 的所有字符(itertools.cycle
的模数版本)。这会产生
>>> many_byte_xor("AABAA", "AB")
'\x00\x03\x03\x03\x00'
>>> many_byte_xor("ABCDABCD", "ABCD")
'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> many_byte_xor("ABCDABCDA", "ABCD")
'\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> many_byte_xor("ABCDABCDAB", "ABCD")
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> many_byte_xor("ABCDABCDAB", "ABC")
'\x00\x00\x00\x05\x03\x01\x02\x06\x02\x03'
哪个 IIUC 是您想要的。
关于python - 了解 Python struct.pack 和二进制输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11494596/