Last active
December 18, 2015 23:09
-
-
Save marcguyer/5860026 to your computer and use it in GitHub Desktop.
A c# example for verifying a CheddarGetter webhook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Grab The Authorization Header | |
var authorizationHeader = request.Headers["X-CG-SIGNATURE"]; | |
if (string.IsNullOrEmpty(authorizationHeader)) | |
{ | |
throw new Domain.Exceptions.Exception(); | |
} | |
request.InputStream.Seek(0, SeekOrigin.Begin); | |
using (var reader = new StreamReader(request.InputStream)) | |
{ | |
// Read The Entire Body In | |
var httpBody = reader.ReadToEnd(); | |
// Get Token | |
var token = CalculateMd5Hash(httpBody); | |
// Get SHA256 HMAC Hash of the MD5 hash using my secret key as the salt | |
var sha256String = CalculateSha256Hash(_secretKey, token); | |
// Check Against The Authorization Header | |
if (sha256String != authorizationHeader) | |
{ | |
throw new Domain.Exceptions.Exception(); | |
} | |
} | |
public string CalculateMd5Hash(string input) | |
{ | |
// fire up a new MD5 creator | |
var md5 = MD5.Create(); | |
// convert input to a byte array | |
var inputBytes = Encoding.ASCII.GetBytes(input); | |
// get the byte array hash | |
var hash = md5.ComputeHash(inputBytes); | |
// convert the byte array to a string and return | |
var sb = new StringBuilder(); | |
for (var i = 0; i < hash.Length; i++) | |
{ | |
sb.Append(hash[i].ToString("x2")); | |
} | |
return sb.ToString(); | |
} | |
public string CalculateSha256Hash(string secretKey,string md5) | |
{ | |
// Get The Byte Array of My Secret Key | |
var secretKeyArray = Encoding.ASCII.GetBytes(secretKey); | |
// Build A SHA256 Hash Creator Using My Secret Key as the key | |
var hash = new HMACSHA256(secretKeyArray); | |
var byteArray = hash.ComputeHash(Encoding.ASCII.GetBytes(md5)); | |
// convert the byte array to a string and return | |
var sb = new StringBuilder(); | |
for (var i = 0; i < byteArray.Length; i++) | |
{ | |
sb.Append(byteArray[i].ToString("x2")); | |
} | |
return sb.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Marc,
For the CalculateSha256Hash method, the var hash is the actual hash object, you need to do the compute hash with the md5 string using that hash object. I updated your code with the updates, but it's still not matching up. Here is the updated code