Skip to content

Instantly share code, notes, and snippets.

@Donnotron666
Created March 8, 2017 23:08
Show Gist options
  • Save Donnotron666/71928a7e60d49a09270dd25654568893 to your computer and use it in GitHub Desktop.
Save Donnotron666/71928a7e60d49a09270dd25654568893 to your computer and use it in GitHub Desktop.
using System;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace RequestSigningPOC
{
public static class SigningExtension
{
static Encoding StringEncoding = Encoding.UTF8;
//main entry point
public static String Sign(this HttpWebRequest req, String key)
{
var normalized = req.NormalizedSignature();
//key. Using a hardcoded value for now to compare signing results across languages
var signature = Encrypt(normalized, key);
req.Headers.Add("Authorization", signature);
return signature;
}
static String Encrypt(string body, string key)
{
using (HMACSHA256 hmac = new HMACSHA256(StringEncoding.GetBytes(key)))
{
return Convert.ToBase64String(hmac.ComputeHash(StringEncoding.GetBytes(body)));
}
}
public static String BuildExt(this HttpWebRequest req)
{
//if actually implemented, this would flatten and sort the body
var flattenedAndSorted = "flattenedAndSorted";
//replace all illegal characters in the flattenedAndSorted; (["{\[\]}:,\\])
using (MD5 md5 = MD5.Create())
{
var md5Bytes = md5.ComputeHash(StringEncoding.GetBytes(flattenedAndSorted));
return Convert.ToBase64String(md5Bytes);
}
}
public static string NormalizedSignature(this HttpWebRequest req)
{
var ts = 666;
//nonce. Using a hardcoded value for now compare signing results across languages
var nonce = 666;
//method
var method = req.Method;
//request_uri. I have no idea if Path+Query is appropriate
var uri = req.RequestUri.AbsoluteUri;
//host
var host = req.Host;
//port
var port = req.RequestUri.Port;
//ext
var ext = req.BuildExt();
return new StringBuilder()
.AppendLine(ts.ToString())
.AppendLine(nonce.ToString())
.AppendLine(method.ToLower())
.AppendLine(uri.ToLower())
.AppendLine(host.ToLower())
.AppendLine(port.ToString())
.AppendLine(ext)
.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment