Skip to main content

Groovy HMAC/SHA256 representation

Recently I was working on a grails project that consumes service hooks from another web application. As part of API authentication, I was required to use the sha256 algorithm to generate an HMAC hash of a "calculated token" using a "secret key" as the salt. The following is what worked for me after several unsuccessful attempts (it's mainly java code):

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;

/**

  * @param 
secretKey
  * @param data
  * @return 
HMAC/SHA256 representation of the given string
  */
def hmac_sha256(String secretKey, String data) {

try { SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256")
Mac mac = Mac.getInstance("HmacSHA256")
mac.init(secretKeySpec)
byte[] digest = mac.doFinal(data.getBytes("UTF-8"))
return byteArrayToString(digest)
} catch (InvalidKeyException e) { throw new RuntimeException("Invalid key exception while converting to HMac SHA256")
}
}


private def byteArrayToString(byte[] data) {
BigInteger bigInteger = new BigInteger(1, data)
String hash = bigInteger.toString(16)
//Zero pad it
while (hash.length() < 64) {
hash = "0" + hash
}
return hash
}

To generate SHA256 HMAC hash, call the method hmac_sha256 supplying the required parameters as as shown below:

hmac_sha256("The secret key", "The data to hash")

Hint: You can use other SHA hashing algorithms in place of "HmacSHA256" e.g. HmacSHA1.

Comments

  1. Very cool. Thanks for this! I referenced your post and adapted the code in one of my own posts.

    ReplyDelete

Post a Comment

Popular posts from this blog

Dell BIOS Update on Linux

BIOS updates are mostly supported in Windows Systems, however you can easily accomplish the same on a Dell machine using a Linux System.  NB: For this guide, Dell Inspirion 1545 running Ubuntu 10.04 (Lucid Lynx) was used.  Steps are as follows: Install libsmbios   # sudo apt-get update   # sudo apt-get  install libsmbios-bin Get the System ID       # sudo  getSystemId Visit  http://linux.dell.com/repo/firmware/bios-hdrs/ . Scroll down the list to find a directory that matches the System ID obtained above (and is the latest version). The directory will be named: system_bios_ven_0x1028_dev_SYSTEM_ID_version_BIOS_VERSION.  Go into this directory and download the file, "bios.hdr".   # wget http://linux.dell.com/repo/firmware/bios      hdrs/system_bios_ven_0x1028_dev_0x02aa_version_a14/bios.hdr Load the dell_rbu driver   # sudo modprobe dell_rbu Update the bios   # sudo  dellBiosUpdate -u -f ./bios.hdr Reboot the system for the staged BIOS update to ta