java-How to get SHA or MD5 from a binary file by using java

1. The purpose of this post

I would demo how to use java to get SHA or MD5 from a binary file.

2. Environments

  • java 1.8+
  • apache commons codec 1.13+

3. Solution and Code

3.1 The maven dependency

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.13</version>
</dependency>

3.2 The code

String filePath = "/opt/test.zip";

String md5 = DigestUtils.md5Hex(new FileInputStream(new File(filePath))); //get MD5 

String sha256 = DigestUtils.sha256Hex(new FileInputStream(new File(filePath))); // get SHA256