Java : Creating SHA-1 Signature

This page last changed on Jul 03, 2006 by Kees de Kooter

The Code

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

/**
 * @author Kees de Kooter (kees@boplicity.net)
 * 
 */
public class ShaSignature {

    public String getSignature(String payload) {

        String signature = null;

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(payload.getBytes());
            byte[] hashBytes = messageDigest.digest();

            StringBuffer stringBuffer = new StringBuffer();

            // Convert bytes to string
            for (int i = 0; i < hashBytes.length; i++) {
                String plainText = Integer.toHexString(0xFF & hashBytes[i]);

                if (plainText.length() < 2) stringBuffer.append("0");

                stringBuffer.append(plainText);
            }

            signature = stringBuffer.toString();

        } catch (NoSuchAlgorithmException e) {
            logger.error(e.toString());
        }

        return signature;
    }
}

References

Online calculation of hashes: http://discodia.org/en/md5