Skip to content

Instantly share code, notes, and snippets.

@MartinThoma
Last active January 16, 2021 14:38
Show Gist options
  • Save MartinThoma/be7232249ae127d8adc301b8052c53c0 to your computer and use it in GitHub Desktop.
Save MartinThoma/be7232249ae127d8adc301b8052c53c0 to your computer and use it in GitHub Desktop.
def xor_hash(input_bytes: bytes) -> bytes:
hash_length = 16 # in bytes
# Get the first 16 bytes
if len(input_bytes) < hash_length:
return input_bytes + b"\0" * (hash_length - len(input_bytes))
hash_value = input_bytes[:hash_length]
# iterate over blocks of the defined length
remaining = input_bytes[hash_length:]
while len(remaining) >= hash_length:
hash_value = xor_bytes(hash_value, remaining[:hash_length])
remaining = remaining[hash_length:]
# take care of remaining bytes
if len(remaining) < hash_length:
hash_value = remaining + b"\0" * (hash_length - len(remaining))
return hash_value
def xor_bytes(xs: bytes, ys: bytes) -> bytes:
"""Run XOR over two b."""
assert len(xs) == len(ys)
return "".join([chr(x ^ y) for x, y in zip(xs, ys)]).encode()
# Try it with an example file
with open("/etc/passwd", "rb") as fp:
data = fp.read()
print(xor_hash(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment