This is a sample program that returns the hash value of a file in java.
SampleMain.java
package test;
public class SampleMain {
public static void main(String[] args) {
System.out.println(SampleHash
.getfileHash("glassfish-5.0.1.zip", SampleHash.SHA_512));
}
}
SampleHash.java
package test;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SampleHash {
/**MD2 algorithm*/
public static final String MD2 = "MD2";
/**MD5 algorithm*/
public static final String MD5 = "MD5";
/** SHA-1 algorithm*/
public static final String SHA_1 = "SHA-1";
/** SHA-256 algorithms*/
public static final String SHA_256 = "SHA-256";
/** SHA-512 algorithm*/
public static final String SHA_512 = "SHA-512";
/**
*Returns the hash value (string) of the file
* @param filePath File path
* @param algorithmName algorithm
* @return hash value (string)
*/
public static String getfileHash(String filePath, String algorithmName) {
Path path = Paths.get(filePath);
byte[] hash = null;
//Algorithm acquisition
MessageDigest md = null;
try {
md = MessageDigest.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try (
//Input stream generation
DigestInputStream dis = new DigestInputStream(
new BufferedInputStream(Files.newInputStream(path)), md)) {
//Read file
while (dis.read() != -1) {
}
//Hash value calculation
hash = md.digest();
} catch (IOException e) {
e.printStackTrace();
}
//Convert hash value (byte) to character string and return
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
String hex = String.format("%02x", b);
sb.append(hex);
}
return sb.toString();
}
}
I'm getting the hash value using java.security.DigestInputStream
and java.security.MessageDigest
.
The acquired hash value (byte) is converted to a character string and returned.
that's all
Recommended Posts