Generate SHA-1 Hash using Java

MessageDigest class

package app;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main
{
    public static void main(String[] args) throws NoSuchAlgorithmException
    {
        String text = "Hello";
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.update(text.getBytes(StandardCharsets.UTF_8));

        byte[] bytes = crypt.digest();
        BigInteger bi = new BigInteger(1, bytes);
        String digest = String.format("%0" + (bytes.length << 1) + "x", bi);

        System.out.println(digest);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.