Sample program that returns the hash value of a file in Java

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

Sample program that returns the hash value of a file in Java
Determine that the value is a multiple of 〇 in Ruby
A program that counts the number of words in a List
Sample code to assign a value in a property file to a field of the expected type
Get the public URL of a private Flickr file in Java
[Java] Returns a Japanese name file in filename of HTTP header
A program (Java) that outputs the sum of odd and even numbers in an array
The story of forgetting to close a file in Java and failing
Measure the size of a folder in Java
A bat file that uses Java in windows
Creating a sample program using the problem of a database specialist in DDD Improvement 2
[Java] Get the file in the jar regardless of the environment
[Java] Integer information of characters in a text file acquired by the read () method
A quick explanation of the five types of static in Java
Activate Excel file A1 cell of each sheet in Java
Unzip the zip file in Java
A simple sample callback in Java
Order of processing in the program
I made a program in Java that solves the traveling salesman problem with a genetic algorithm
Let's create a TODO application in Java 5 Switch the display of TODO
Form that receives the value of the repeating item in Spring MVC
Sample code that uses the Mustache template engine JMustache in Java
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
Get the result of POST in Java
The story of writing Java in Emacs
Sample to unzip gz file in Java
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
Declare a method that has a Java return value with the return value data type
A collection of phrases that impresses the "different feeling" of Java and JavaScript
Procedure to make the value of the property file visible in Spring Boot
Memo: [Java] If a file is in the monitored directory, process it.
This and that of the implementation of date judgment within the period in Java
How to find out the Java version of a compiled class file
How to change the value of a variable at a breakpoint in intelliJ
How to get the absolute path of a directory running in Java
[Java] Implement a function that uses a class implemented in the Builder pattern
I tried to make a sample program using the problem of database specialist in Domain Driven Design
Java that outputs vmg format file in eml format
I made a primality test program in Java
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
Read a string in a PDF file with Java
About the idea of anonymous classes in Java
A story about the JDK in the Java 11 era
Sample source code for finding the least common multiple of multiple values in Java
Feel the passage of time even in Java
I wrote a primality test program in Java
[Java] Read the file in src / main / resources
A quick review of Java learned in class
Code that deletes all files of the specified prefix in AWS S3 (Java)
Validate the identity token of a user authenticated with AWS Cognito in Java
I wrote a prime factorization program in Java
Import files of the same hierarchy in Java
A story about running a program that copies files in Java from a bat file to make the work done every day a little more efficient
Sample code to get the values of major SQL types in Java + MySQL 8.0
About the solution of the error that occurred when trying to create a Japanese file of devise in the Docker development environment
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
[Ruby] I want to make a program that displays today's day of the week!
The story that the port can no longer be used in the Spring boot sample program
Note (sample code) that added a plant block like Sweet berry of 1.14 in Minecraft 1.12.2