Jump to content
Claris Engage 2025 - March 25-26 Austin Texas ×

This topic is 4230 days old. Please don't post here. Open a new topic instead.

Recommended Posts

Posted

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.

Posted

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.

Posted

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.

Posted

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);

Posted

Thanks Karsten,

 

That worked - I hoped it would be something simple and it was :laugh: .

This topic is 4230 days old. Please don't post here. Open a new topic instead.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.