Lesson 7 of 9
Identifying files by their signatures
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
The first few bytes reveal a file's format
Explanation
Don't trust a file's name or its extension, because an extension can be changed with a click. A file's real format shows in its first bytes, since almost every format starts with a fixed signature, a magic number, written by the program that created the file:
PNG 89 50 4e 47 0d 0a 1a 0a b"\x89PNG\r\n\x1a\n" ZIP 50 4b 03 04 b"PK\x03\x04" GIF 47 49 46 38 39 61 b"GIF89a" PDF 25 50 44 46 b"%PDF" ELF 7f 45 4c 46 b"\x7fELF"
You've seen some of these signatures without noticing. The letters PK at the start of every ZIP file are the initials of the format's creator, Phil Katz, and modern Word and Excel files are really ZIP archives. ELF is the format of executable programs on Linux.
Detecting them in Python is easy with data.startswith(sig). It only compares the start, so a file that happens to contain a signature somewhere in the middle won't be mistaken for one that begins with it.
Your task
Write a function detect(data) that returns the file type as a lowercase string, one of "png", "zip", "gif", "pdf" or "elf". If no signature matches, return "unknown".
Checks
6 checks- Detects a PNG image
- Detects a ZIP archive
- Detects a GIF image
- Detects a PDF without confusing it with anything else
- Detects an ELF executable
- Unknown data and near-misses don't fool it