Compute SHA-1 of byte array

Viewed 60305

I'm looking for a way of getting an SHA-1 checksum with a Java byte array as the message.

Should I use a third party tool or is there something built in to the JVM that can help?

8 Answers

The following code converts the given byte[] into a String of the SHA-1 hash.

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public static String hash(byte data[]) throws NoSuchAlgorithmException
{
   MessageDigest digest;
   BigInteger big;
   String result;
   byte hash[];

   digest = MessageDigest.getInstance("SHA-1"); 
   hash   = digest.digest(data);
   big    = new BigInteger(1, hash);
   result = big.toString(16);

   return result;
}

Note: The leading zeros will be trimmed. So, this may or may not work depending on your use case.

Related