Lesson 7 of 9

Identifying files by their signatures

Goal

The first few bytes reveal a file's format

01

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.

02

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
  1. Detects a PNG image
  2. Detects a ZIP archive
  3. Detects a GIF image
  4. Detects a PDF without confusing it with anything else
  5. Detects an ELF executable
  6. Unknown data and near-misses don't fool it
03

Hints

0/3
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.