Skip to content

Instantly share code, notes, and snippets.

@duncansmart
Last active October 20, 2022 06:19
Show Gist options
  • Save duncansmart/3169752 to your computer and use it in GitHub Desktop.
Save duncansmart/3169752 to your computer and use it in GitHub Desktop.
C# implementation of "Securing Webhooks" sample code https://documentation.mailgun.com/user_manual.html#webhooks
using System;
using System.Text;
using System.Security.Cryptography;
class MailgunUtil
{
/// <summary>
/// Authenticates incoming requests to a Mailgun webhook (https://documentation.mailgun.com/user_manual.html#webhooks).
/// </summary>
/// <example>
/// <code>bool verified = MailgunUtil.Verify(API_KEY, Request.Form["token"], Request.Form["timestamp"], Request.Form["signature"])</code>
/// </example>
public static bool Verify(string apikey, string token, string timestamp, string signature)
{
var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(apikey));
var sigBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(timestamp + token));
string sigString = BitConverter.ToString(sigBytes).Replace("-", "");
return signature.Equals(sigString, StringComparison.OrdinalIgnoreCase);
}
}
@MitchStephan
Copy link

I was having trouble implementing this and your snippet worked great, thanks.

@gavinkilbride
Copy link

Useful little Gist, thanks.

@kraghavk
Copy link

kraghavk commented Feb 2, 2017

Thanks! That was helpful

@csxcode
Copy link

csxcode commented Aug 24, 2017

Thank you so much, sir!!!!

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