The SHA1 hash can be generated using DigestUtils
from Apache commons.
sha1 = org.apache.commons.codec.digest.DigestUtils.sha1Hex( value );
The SHA1 hash can also be generated directly using the MessageDigest
class from the jdk:
MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(value.getBytes("utf8")); sha1 = String.format("%040x", new BigInteger(1, digest.digest()));
Here is an example creating the sha1 of the String "this is a test". First is uses the method using the MessageDigest
class from the jdk. Then it uses the DigestUtils
class from Apache commons. The generated sha1 are written in the console.
import java.math.BigInteger; import java.security.MessageDigest; public class SHA1 { public static void main(String[] argv){ String value = "this is a test"; String sha1 = ""; // With the java libraries try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(value.getBytes("utf8")); sha1 = String.format("%040x", new BigInteger(1, digest.digest())); } catch (Exception e){ e.printStackTrace(); } System.out.println( "The sha1 of \""+ value + "\" is:"); System.out.println( sha1 ); System.out.println(); // With Apache commons sha1 = org.apache.commons.codec.digest.DigestUtils.sha1Hex( value ); System.out.println( "The sha1 of \""+ value + "\" is:"); System.out.println( sha1 ); } }
The sha1 of "this is a test" is: fa26be19de6bff93f70bc2308434e4a440bbad02 The sha1 of "this is a test" is: fa26be19de6bff93f70bc2308434e4a440bbad02