Understanding Python Struct.pack And Binary Input
The following function accepts a binary 4 byte key for key. buf is binary input which is xor'd against the 4 byte key. def four_byte_xor(buf, key): #key = struct.pack(b'>I',
Solution 1:
Sure, you can modify the function to accept varying key lengths. For example, something like
defmany_byte_xor(buf, key):
buf = bytearray(buf)
for i, bufbyte inenumerate(buf):
buf[i] = chr(bufbyte ^ ord(key[i % len(key)]))
returnstr(buf)
which cycles over all the characters of the key (the modulus version of itertools.cycle
). This produces
>>> 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'
which IIUC is what you want.
Post a Comment for "Understanding Python Struct.pack And Binary Input"