How to use magic bytes to identify files using python
Solution 1:
Your code needed a bit of tweaking, by prefixing the word png
with a dot, you're making it seem as if the file has an extension. Also, print file_head
. Run this:
import glob, os
magic_numbers = {'png': bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])}
max_read_size = max(len(m) for m in magic_numbers.values()) # get max size of magic numbers of the dict
os.chdir("/tmp")
for x in glob.glob("*png"):
with open(x, 'rb') as fd:
file_head = fd.read()
print(file_head)
if file_head.startswith(magic_numbers['png']):
print("It's a PNG File")
else:
print("no")
It should print something like this:
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82The flag is: 2NECGNQM4GD3QPD' It's a PNG File
Your flag will probably be different from mine.
Cheers!