logo

Java Generate SHA-1 using DigestUtils in Apache Commons Codec

In below code example you will learn how to use org.apache.commons.codec.digest.DigestUtils class in Apache Commons Codec to generate SHA-1 string in Java.

Adding Apache Commons Codec Dependency

Define below dependency in build.gradle if you are using gradle.

compile group: 'commons-codec', name: 'commons-codec', version: '1.12'

Define this dependency in pom.xml if you are using maven.

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

Or you can download the release from Apache Commons Codec home page at: here

Generate SHA-1 for a string

String inputData = "https://simplesolution.dev/";
String sha1Value = DigestUtils.sha1Hex(inputData);

Generate SHA-1 for a file

The code example below to generate SHA-1 with input data is a file located at D:\sample.txt

InputStream inputStream  = new FileInputStream("D:\\sample.txt");
String sha1Value = DigestUtils.sha1Hex(inputStream);

Full code example:

package simplesolution.dev;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.FileInputStream;
import java.io.InputStream;

public class DigestUtilsAndSHA1Samples {

    public static void main(String... args) throws Exception {
        generateSha1ForString();

        generateSha1ForInputStream();
    }

    private static void generateSha1ForString() {
        String inputData = "https://simplesolution.dev/";
        String sha1Value = DigestUtils.sha1Hex(inputData);

        System.out.println(sha1Value);
    }

    private static void generateSha1ForInputStream() throws Exception {
        InputStream inputStream  = new FileInputStream("D:\\sample.txt");
        String sha1Value = DigestUtils.sha1Hex(inputStream);

        System.out.println(sha1Value);
    }
}

Happy Coding!