Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
C# Mashape Authentication
// Put the "header" value into a "X-Mashape-Authorization" header before making the HTTP request
// Util functions to generate a HMAC_SHA1 hash and Base64 encode a value
private static String hmac_sha1(String publicKey, String privateKey) {
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] privateKeyBytes = encoding.GetBytes(privateKey);
byte[] publicKeyBytes = encoding.GetBytes(publicKey);
HMACSHA1 hmacsha1 = new HMACSHA1(privateKeyBytes);
byte[] hash = hmacsha1.ComputeHash(publicKeyBytes);
return BitConverter.ToString(hash).Replace("-","").ToLower();
private static String EncodeTo64(string toEncode)
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
String returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
// Sample code using the functions above
static void Main(string[] args)
String publicKey = "PUBLIC_KEY";
String hash = hmac_sha1(publicKey, "PRIVATE_KEY");
// Here we go, this is the final header value generated according to the spec:
String header = EncodeTo64(publicKey + ":" + hash);
// For example, let's use the header value above in the following GET request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
// Set the header
request.Headers.Add("X-Mashape-Authorization", header);
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
StreamReader resStream = new StreamReader(httpResponse.GetResponseStream());
// This is the response stream converted to String
String stringResponse = resStream.ReadToEnd();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment