Skip to content

Instantly share code, notes, and snippets.

@USA-RedDragon
Last active October 22, 2023 10:27
Show Gist options
  • Save USA-RedDragon/f327e0716ca6583a8ebdf963dff18595 to your computer and use it in GitHub Desktop.
Save USA-RedDragon/f327e0716ca6583a8ebdf963dff18595 to your computer and use it in GitHub Desktop.
TARGET = b"\xDE\xAD\xBE\xEF"
import random
def generateTestFile():
with open("test.bin", "wb") as f:
randData = bytes(random.getrandbits(8) for _ in range(1024))
f.write(randData)
# Grab a random number and place the bytes 0xDEADBEEF in that location
randOffset = random.randint(0, 1024)
f.seek(randOffset)
f.write(b"\xDE\xAD\xBE\xEF")
print(f"Wrote 0xDEADBEEF at offset: {hex(randOffset)}")
def find():
foundBytes = 0
offset = 0
with open("test.bin", "rb") as f:
chunk = f.read(512)
while chunk:
for byte in chunk:
offset += 1
if byte == TARGET[foundBytes]:
# print(f"Found byte: {hex(byte)} matching {TARGET[foundBytes]} at offset: {hex(offset)}")
foundBytes += 1
else:
# Avoid ignoring a byte if it's the first byte of the target
if byte == TARGET[0]:
foundBytes = 1
continue
# if foundBytes > 0:
# print(f"Byte: {hex(byte)} does not match target byte: {hex(TARGET[foundBytes])}, resetting")
foundBytes = 0
if foundBytes == len(TARGET):
print(f"Found the 4 bytes at offset: {hex(offset-4)}")
return True
chunk = f.read(512)
# print(f"Reached end of file at offset: {hex(offset)}")
return False
# Run find until it fails
generateTestFile()
while find():
generateTestFile()
print("Failed to find the bytes")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment