How to Generate the MD5 Checksum for a File in Java
Generate the MD5 Checksum for a File in Java
MD5 (Message-Digest Algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value. It's very popular because it is fast and easy to use. The purpose of using this algorithm is to verify data integrity. For example, if two files have the same MD5 checksum, it implies that the two files are exactly identical.
In this tutorial, we will show you how to generate the MD5 checksum for a file in Java.
Prerequisites
- A computer with a running operating system (OS)
- Java 8 or later installed on the computer
Steps to Generate the MD5 Checksum for a File in Java
- Create a Java file with the following code:
import java.io.FileInputStream; import java.security.MessageDigest; public class MD5Checksum { public static String getMD5Checksum(String filename) throws Exception { byte[] b = createChecksum(filename); String result = ""; for (int i=0; i < b.length; i++) { result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ); } return result; } private static byte[] createChecksum(String filename) throws Exception { InputStream fis = new FileInputStream(filename); byte[] buffer = new byte[1024]; MessageDigest complete = MessageDigest.getInstance("MD5"); int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); return complete.digest(); } }
- Compile the code
javac MD5Checksum.java
- Run the code
java MD5Checksum path/to/yourfile.ext
- The output will be the MD5 checksum of the file.
Conclusion
In this tutorial, we have shown you how to generate the MD5 checksum for a file in Java. We hope this information has been helpful.