How to Use File Magic Numbers to Secure File Uploads in Java

This article explains why relying on file extensions is unsafe, introduces the concept of file magic numbers, lists common file signatures, and provides Java code to read the first 28 bytes of an uploaded file for robust type verification, reducing upload vulnerabilities.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Use File Magic Numbers to Secure File Uploads in Java

Uploading files poses high security risks; the most basic defense is to verify that the file type is allowed.

Simply checking the file extension is unreliable; a more secure method is needed.

Many file types have fixed initial bytes called "magic numbers", which can be used to identify the file type.

To prevent file upload attacks, read the first 28 bytes of the uploaded file, convert them to hexadecimal, and compare with known magic numbers.

Common file type magic numbers

JPEG – FFD8FF

PNG – 89504E47

GIF – 47494638

BMP – 424D

PDF – 255044462D312E

ZIP – 504B0304

RAR – 52617221

WAV – 57415645

AVI – 41564920

Java example for reading file headers

byte[] b = new byte[28];
InputStream is = new FileInputStream(file_path);
is.read(b,0,28);
is.close();
String hex = bytes2hex(b);
String fileHead = hex.toUpperCase();

This method provides stricter file type validation and reduces the risk of file upload vulnerabilities, though it may not guarantee absolute security; for higher security, using a dedicated resource server is recommended.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

file uploadfile validationmagic numbers
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.