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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
