May 3, 201312 yr Hi, I'm trying to generate an SHA-256 Hmac hash of some text and a key using ScriptMaster. Basically I need to create a version of the PHP hash_hmac command. I've tried the following code and it generates a hash but it isn't correct. Here's the script: SHA_Hash (text;key) import javax.crypto.Mac; private static String toHex(byte[] hash){ StringBuffer buf = new StringBuffer(hash.length * 2); for (int i=0; i<hash.length; i++) { byte element = hash; int intVal = element & 0xff; if (intVal < 0x10){ // append a zero before a one digit hex // number to make it two digits. buf.append("0"); } buf.append(Integer.toHexString(intVal)); } return buf.toString(); } // generate hash def hashkey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "HmacSHA256"); def digest = Mac.getInstance("HmacSHA256"); digest.init(hashkey); def rawSig = digest.doFinal(text.getBytes()); def sig = new sun.misc.BASE64Encoder().encode(rawSig); byte[] hash = sig; return toHex(hash); It's probably a simple error but my Groovy and SHA-256 knowledge isn't good enough to find out what's wrong. Any ideas? I'm sure this would be a useful function for others too. Thanks.
May 3, 201312 yr Author see http://fmforums.com/forum/topic/86849-sha256-encryption/ I saw that thread and it was useful but won't work with a pass key (not Hmac SHA-256).
May 4, 201312 yr Ah. I see. I use it only for identifying files; I was not aware of hmac. The error I get says that "HmacSHA256" is not available. Other demos I found on the web yield the same result. What was your error message? Only the first line of the ScriptMaster.fp7 error dialog.
May 5, 201312 yr Author The script generates a hash but it's not correct (when I generate the hash manually it's different). I am using this to download information via a a proprietary web-based API. They require a Hmac Hash for validation.
May 6, 201312 yr Solution Looking at your code again I see that you're returning the hex encoded base64 string. Is that really needed by your API? Usually you either encode base64 OR hex, not both. Perhaps the last lines in your script should read: digest.init(hashkey); def rawSig = digest.doFinal(text.getBytes()); //def sig = new sun.misc.BASE64Encoder().encode(rawSig); //byte[] hash = sig; byte[] hash = rawSig; return toHex(hash);
May 6, 201312 yr Author Thanks Karsten, That worked - I hoped it would be something simple and it was .
Create an account or sign in to comment