Generate HMAC with SHA1 Hash

0
I’m needing to generate an HMAC using a SHA1 hash in order to validate that a webhook created by GitHub and sent to my published REST service really came from GitHub.  Documentation here.   I saw in the Community Commons App Store Module a function to generate a HMAC with a SHA256 hash but nothing for SHA1. Can someone point me to a way to do this or do I need to create a Java Action for this?
asked
1 answers
4

Hi Paul.

I contributed the HMAC SHA256 to Community Commons as I had a similar problem to you with my app needing to authenticate to a third party service.

I would suggest you use a Java Action. The following should do the trick.

Create a module called “HMACSHA1” and add a Java Action called “GenerateHMAC_SHA1” that takes two string parameters, “key” and “valueToEncrypt”. Add the following code to the Java source for the action.

// This file was generated by Mendix Studio Pro.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.

package hmacsha1.actions;

import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import java.util.Formatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class GenerateHMAC_SHA1 extends CustomJavaAction<java.lang.String>
{
	private java.lang.String key;
	private java.lang.String valueToEncrypt;

	public GenerateHMAC_SHA1(IContext context, java.lang.String key, java.lang.String valueToEncrypt)
	{
		super(context);
		this.key = key;
		this.valueToEncrypt = valueToEncrypt;
	}

	@java.lang.Override
	public java.lang.String executeAction() throws Exception
	{
		// BEGIN USER CODE
		SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(secretKey);
		mac.update(valueToEncrypt.getBytes("UTF-8"));

		Formatter formatter = new Formatter();

		for (byte b : mac.doFinal()) {
			formatter.format("%02x", b);
		}

		return formatter.toString();
		// END USER CODE
	}

	/**
	 * Returns a string representation of this action
	 */
	@java.lang.Override
	public java.lang.String toString()
	{
		return "GenerateHMAC_SHA1";
	}

	// BEGIN EXTRA CODE
	// END EXTRA CODE
}


Hope this helps.

answered