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;
}
}
import java.io.File;
public class FileChecksumExample {
public static void main(String[] args) throws Exception {
File file = new File("f:\\Fedora-KDE-Live-x86_64-34-1.2.iso");
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) {
StringBuilder result = new StringBuilder();
for (byte aByte : bytes) {
result.append(String.format("%02x", aByte));
// upper case
// result.append(String.format("%02X", aByte));
}
return result.toString();
}
}