How to Calculate File Checksum MD5, SHA in Java
A checksum is used to ensure the integrity of a file after it has been transmitted from one storage device to another. It is a way to ensure that the transmitted file is exactly the same as the source file. It functions as a fingerprint of that file. The checksum or hash sum is calculated using a hash function. In this tutorial we will show you how to calculate file checksum using MD5 and SHA algorithms.
Calculate File Checksum
Here is a class that will generate a checksum hash in one of the registered hash algorithms like MD5 or SHA. This class allows you to simply create a checksum of a file using one of the popular hashing algorithms.
package com.memorynotfound.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public enum Hash {
MD5("MD5"),
SHA1("SHA1"),
SHA256("SHA-256"),
SHA512("SHA-512");
private String name;
Hash(String name) {
this.name = name;
}
public String getName() {
return name;
}
public byte[] checksum(File input) {
try (InputStream in = new FileInputStream(input)) {
MessageDigest digest = MessageDigest.getInstance(getName());
byte[] block = new byte[4096];
int length;
while ((length = in.read(block)) > 0) {
digest.update(block, 0, length);
}
return digest.digest();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Creating a checksum of a File
Using this class to calculate file checksum is very straight forward.
package com.memorynotfound.file;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
public class FileChecksumExample {
public static void main(String[] args) throws Exception {
File file = new File("/tmp/test.pdf");
System.out.println("MD5 : " + toHex(Hash.MD5.checksum(file)));
System.out.println("SHA1 : " + toHex(Hash.SHA1.checksum(file)));
System.out.println("SHA256 : " + toHex(Hash.SHA256.checksum(file)));
System.out.println("SHA512 : " + toHex(Hash.SHA512.checksum(file)));
}
private static String toHex(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes);
}
}
Output
The result is different file checksums for different algorithms. You can use this checksum as a fingerprint for your file.
MD5 : C58FB4E4ABBAE09557566ED313C18DDB
SHA1 : 8489CEBDF4AC646417E2AAC108AB643AA8299BEE
SHA256 : 53D2ED4AABBE64D4B93A79BA1B579FCAFB53C8890443DE8200F021671322382A
SHA512 : 395294CE9D805B18FA2DFE86DF7F25932DE773451D4EFAA387131429F50EF60F1465FFC1EDCAD77C10C99D88EBBB668A312534ACC34CFF459155B224DD50DFD3