HomeGuidesUnderstanding Magic Bytes: How File Signatures Prevent Malicious File Uploads
Security & Privacy7 min readUpdated 2026-11-05

Understanding Magic Bytes: How File Signatures Prevent Malicious File Uploads

Learn how to inspect file magic numbers, detect polyglot files, and implement secure client-side file validation.

Need to do this immediately?

Use our free, private client-side browser tool with zero installation.

Inspect File Metadata with DocSwift
Relying on a file's extension (like .pdf or .jpg) or the user-supplied Content-Type header to validate file uploads is one of the most dangerous vulnerabilities in modern web applications. Attackers routinely rename executable scripts to 'avatar.jpg' to bypass naive upload filters. The only defense is inspecting Magic Bytes.

What Are Magic Bytes?

Magic bytes (file signatures) are specific hexadecimal byte sequences placed at the very beginning (offset 0) of a binary file that identify its true file format.

For example, every genuine PDF file begins with 25 50 44 46 (%PDF-), and every PNG begins with 89 50 4E 47 0D 0A 1A 0A. Regardless of what the file is named, its magic bytes reveal its true identity.

Validating File Signatures in JavaScript via FileReader

In modern web applications, you can read the first 4 to 8 bytes of an uploaded Blob using FileReader and an ArrayBuffer.

By checking new Uint8Array(buffer).slice(0, 4) against known signature tables, you verify genuine files before executing further client-side or server-side logic.

Pro Tip:Beware of polyglot files (files that are simultaneously valid under two formats, like a valid GIF and a valid JavaScript file).

Step-by-Step Tutorial

1

Slice the Initial Binary Header

Read the first 8 to 16 bytes of the file blob using FileReader.readAsArrayBuffer().

2

Compare Against Known Signature Tables

Match the extracted hex string against standard magic byte dictionaries.

3

Reject Mismatched Extensions

If a file named 'invoice.pdf' does not start with 25 50 44 46, reject it immediately.

Ready to Try It Yourself?

DocSwift processes everything directly on your device. Fast, safe, and completely free forever.

How helpful was this guide?

Rated 4.9 / 5 by 3,420+ users worldwide

Share with Colleagues & Friends

Help others protect their document privacy

Frequently Asked Questions

Can an attacker fake magic bytes?

An attacker can prepend magic bytes to a malicious script, but a strict binary parser (like a true PDF or image decoder) will fail to parse subsequent corrupted structures.

Where can I look up magic bytes for any format?

Explore DocSwift's File Formats Encyclopedia (/formats/) for verified hex signatures across all major file types.