PNG, Not TXT: Identifying a File by Its Signature Bytes
The challenge
A file called notes.txt showed up in a download folder, but a text editor displays only garbage. Open it in the hex viewer, compare the first bytes to the reference signatures, and type the real file type.
What you'll learn
- Recognise the 8-byte PNG signature 89 50 4E 47 0D 0A 1A 0A
- Read bytes 50 4E 47 as the ASCII letters PNG
- Explain that a text file has no fixed magic and so cannot match this header
- Spot the IHDR chunk that follows every PNG header
- Distinguish PNG from GIF, PDF, and ZIP by their leading bytes
Skills tested
Prerequisites
- Comfort reading hexadecimal byte values
- Awareness that renaming a file does not change its contents
How it works
A file's extension is just part of its name and can be changed in a second, but the bytes inside follow a format. Most binary formats begin with a fixed signature (magic number) that identifies them regardless of the name. A plain text file is the exception: it has no required header, just characters. So if a .txt file starts with a known binary signature, the extension is wrong.
The PNG signature is eight bytes: 89 50 4E 47 0D 0A 1A 0A. The middle three bytes, 50 4E 47, are the ASCII letters PNG. The surrounding bytes are a clever integrity check - the leading 89 is a non-ASCII byte that breaks if the file is mistreated as text, and the 0D 0A 1A 0A tail catches line-ending corruption from transfers that mangle newlines. Immediately after the signature comes the IHDR chunk (you can see 49 48 44 52 = 'IHDR' in the bytes), which carries the image dimensions.
The reference list pits PNG against other images and documents. GIF starts 47 49 46 38 ('GIF8'), PDF starts 25 50 44 46 ('%PDF'), and ZIP starts 50 4B 03 04 ('PK'). None of those match, so the only consistent answer is PNG.
Common mistakes
- Trusting the .txt extension. The name says text, but text files have no magic header and this one clearly does.
- Misreading the leading 89 byte. It is a deliberate non-printable byte; do not let it hide the readable
PNGthat follows. - Confusing PNG with GIF. Both are images, but GIF begins
47 49 46 38, not89 50 4E 47. - Answering 'image' generically. The prompt asks for the specific type and the signature names exactly one: PNG.
How to defend against it
Systems that accept or store files should identify them by content, never by the supplied name or extension.
- Use a content-based type check (libmagic or equivalent) on uploads instead of trusting the extension.
- If you only allow text, reject files whose first bytes match any known binary signature.
- When rendering user content, set the response type from the validated real type, not the claimed one, to avoid content-type confusion.
- Quarantine and review files whose extension and detected type disagree, since a mismatch is often deliberate.