Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Created April 1, 2009 07:49
Show Gist options
  • Star 70 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
  • Save ishikawa/88599 to your computer and use it in GitHub Desktop.
Save ishikawa/88599 to your computer and use it in GitHub Desktop.
Java Sample Code for Calculating HMAC-SHA1 Signatures
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* The <tt>HmacSha1Signature</tt> shows how to calculate
* a message authentication code using HMAC-SHA1 algorithm.
*
* <pre>
* % java -version
* java version "1.6.0_11"
* % javac HmacSha1Signature.java
* % java -ea HmacSha1Signature
* 104152c5bfdca07bc633eebd46199f0255c9f49d
* </pre>
*
*/
public class HmacSha1Signature {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private static String toHexString(byte[] bytes) {
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
return formatter.toString();
}
public static String calculateRFC2104HMAC(String data, String key)
throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
{
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
return toHexString(mac.doFinal(data.getBytes()));
}
public static void main(String[] args) throws Exception {
String hmac = calculateRFC2104HMAC("data", "key");
System.out.println(hmac);
assert hmac.equals("104152c5bfdca07bc633eebd46199f0255c9f49d");
}
}
@chorandrey
Copy link

for Scala (taken answer above):

  import javax.crypto.Mac
  import javax.crypto.spec.SecretKeySpec
  import org.apache.commons.codec.binary.Base64

  def encryptHMACSHA1(value: String, secretKey: String): String = {
    val signingKey = new SecretKeySpec(secretKey.getBytes, "HmacSHA1")
    val mac = Mac.getInstance("HmacSHA1")
    mac.init(signingKey)
    val rawHmac = mac.doFinal(value.getBytes)
    Base64.encodeBase64String(rawHmac)
  }

@ttraub
Copy link

ttraub commented Feb 17, 2021

Perfect for my needs, thanks so much!

@htteng1976
Copy link

Thanks :)

@clauRamirez
Copy link

Thanks!

@wangschang
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment