I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.

As the title says, I had the opportunity to "find the MD5 checksum of a file in Java and get the result as a character string in hexadecimal notation", and I struggled to implement it, so this is a memo. Basically, it is recommended to use some kind of external library (´ ・ ω ・ `)

First, generate the file for which you want the md5 checksum using the following one-liner.

seq 5 | while read x; do cat /dev/urandom | tr -cd 'a-zA-Z0-9' | fold -s5 | xargs -n5 | head -n5 > "sample${x}.txt"; done 

This creates 5 files with randomly arranged alphanumeric characters, and the contents are as follows.

$ find sample*.txt | while read path; do echo "===> ${path} <==="; cat ${path}; done
===> sample1.txt <===
U959b Xxs05 jZ0XH 7Wrew MRmZB
cJlj3 dCEZm qnjbH yy9QM ntuEy
VXKle Se9uc i5UxP mppHQ LnOL2
SNAXl oPGWk JYK7S ovkov JXnJ6
GBlSy frjGp 1wSZ4 Zoiqx ynuaM
===> sample2.txt <===
aSl1p ZNcQt EecBl ie3ox wihqz
svMsD 88Lar BzxXw IfdQT 0QNHI
W3SD4 NQM76 5bZh5 BFhQs G7lmt
LkNq4 cCfMR yOMqX c4AxQ LL7KG
OuOPK GMbH4 IjiGf OFfUK McT3b
===> sample3.txt <===
Eqmhh ioKSo AEMb8 Kdgo8 deFxc
ASilF deSpC 0TIzI ZGM17 OA932
hSGXL LCy8q DDYAC 9hTiF nsDqH
LQRZb k53VV 03NCY RhKjF tVggB
JHmOx wilgw QZov5 StZ2g 9PGjn
===> sample4.txt <===
0Dx9Z 0Md5q w2cUT hp8gq rHIYB
WD6X5 yjyiX DNNyY ZN9Yu IEEkc
P6LnO Zlxwq wSopY Ke4KH oBAWh
3REUX sMPCU 50VYL X14A4 UWuMy
6bttJ 7DuHi i1zxV WlbAS LFANI
===> sample5.txt <===
8wOUf 80uxv zAHmA k9Yml knvKl
o61Cs CREZm APeOv 0wL1w mNIVs
gWELy HtwT4 MWdgT 8VRqs drYhR
6UJvA koZSX qNL9w elNTS CKKne
r2Jop WlMWG 1Qwep 5yvBS 2dtCx

Then, for the 5 generated files, use the md5sum command to find the MD5 checksum, and you should see something like this:

$ md5sum sample*.txt
6777566a705dd85f1f0c2968bfcab2c8  sample1.txt
be520478d070207d07a3335d0ee2e2a4  sample2.txt
4c47ca20b16046a13dbe50869bba368e  sample3.txt
48ca253e12841800cf898ab090a04a0e  sample4.txt
b378511f4b8878c338d602e5376f8426  sample5.txt

Although the introduction has become long, the Java code that asks for the md5 checksum of the main subject is as follows.

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;
import java.util.List;


public class Main {
	public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
		var filenames = List.of(
			"sample1.txt",
			"sample2.txt",
			"sample3.txt",
			"sample4.txt",
			"sample5.txt"
		);
		
		for (var filename : filenames) {
			var md5 = md5sum(Paths.get(filename));
			System.out.printf("%s  %s%n", md5, filename);
		}
	}
	
	public static String md5sum(Path path) throws NoSuchAlgorithmException, IOException {
		var digest = MessageDigest.getInstance("MD5");
		try (var input = new DigestInputStream(Files.newInputStream(path), digest)) {
			while (input.read() != -1) {
				// PASS;
			}
			
			var hash = new StringBuilder();
			for (byte b : digest.digest()) {
				hash.append(String.format("%02x", b));
			}
			return hash.toString();
		} 
	}
}

If you do this, you will get output similar to the following: Since it matches the result of the md5sum command, it can be said that it was able to be obtained correctly (´ ・ ω ・ `).

6777566a705dd85f1f0c2968bfcab2c8  sample1.txt
be520478d070207d07a3335d0ee2e2a4  sample2.txt
4c47ca20b16046a13dbe50869bba368e  sample3.txt
48ca253e12841800cf898ab090a04a0e  sample4.txt
b378511f4b8878c338d602e5376f8426  sample5.txt

Also unconfirmed, the part of the above Java code that says var digest = MessageDigest.getInstance ("MD5"); is replaced withvar digest = MessageDigest.getInstance ("SHA-1");andvar digest = MessageDigest.getInstance. If you change it to ("SHA-256");, you can also get the SHA-1 and SHA-2 checksums.

Recommended Posts

I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
I want to get a list of the contents of a zip file and its uncompressed size
The story of forgetting to close a file in Java and failing
I want to recursively get the superclass and interface of a certain class
# 1_JAVA I want to get the index number by specifying one character in the character string.
Convert a Java byte array to a string in hexadecimal notation
I want to find out which version of java the jar file I have is available
Get the public URL of a private Flickr file in Java
I tried to summarize the methods of Java String and StringBuilder
How to get the length of an audio file in java
Get the result of POST in Java
How to get the current date as a string in yyyyMMdd format
How to find out the Java version of a compiled class file
[Java] How to get to the front of a specific string using the String class
I want to get the IP address when connecting to Wi-Fi in Java
How to get the absolute path of a directory running in Java
I want to get the field name of the [Java] field. (Old tale tone)
I want to get the value in Ruby
I want to get a list of only unique character strings by excluding fixed character strings from the file name
[Java] Get the file in the jar regardless of the environment
Pass arguments to the method and receive the result of the operation as a return value
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
[Java] I want to convert a byte array to a hexadecimal number
I want to find a relative path in a situation using Path
I tried to summarize the basics of kotlin and java
I want to make a list with kotlin and java!
I want to call a method and count the number
I want to make a function with kotlin and java!
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I tried to convert a string to a LocalDate type in Java
I want to create a Parquet file even in Ruby
I tried to make a client of RESAS-API in Java
I want to simplify the conditional if-else statement in Java
When I switched to IntelliJ, I got a lot of differences in the encoding of the properties file.
In Java, I want to trim multiple specified characters from only the beginning and end.
[Swift] When you want to know if the number of characters in a String matches a certain number ...
[Java] Get the dates of the past Monday and Sunday in order
I want to return to the previous screen with kotlin and java!
I tried to express the result of before and after of Date class with a number line
I want to get some properties as JSON strings in Jackson!
[Wire Mock] I want to set up a stub / mock server in Java and perform E2E tests.
[Java] I felt as a java beginner. "Why is the first letter of the String type capitalized?" I faced the String type.
[Java] I want to perform distinct with the key in the object
[Java] How to convert from String to Path type and get the path
I made a tool to output the difference of CSV file
How to check for the contents of a java fixed-length string
I want to change the value of Attribute in Selenium of Ruby
[Android] I want to get the listener from the button in ListView
I want to download a file on the Internet using Ruby and save it locally (with caution)
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
[Ruby] I want to output only the odd-numbered characters in the character string
[Rails] I want to send data of different models in a form
I want to display images with REST Controller of Java and Spring!
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
[Ruby] I want to extract only the value of the hash and only the key
I want to pass the argument of Annotation and the argument of the calling method to aspect
How to find the total number of pages when paging in Java
Sample program that returns the hash value of a file in Java
Find the maximum and minimum of the five numbers you entered in Java
I want to ForEach an array with a Lambda expression in Java
I translated the grammar of R and Java [Updated from time to time]