Sample C# Script: Generate Signature

This code shows an example of how to generate a signature for API requests. It assumes a token for a user has already been received. Requesting the token for a user is outside of the scope of this article.

using System;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
public class Program
	 * SignData
	 * Takes a sorted list and token, and returns a base 64 encoded signature of the sorted list
	 * stringified and hmac md5 encoded using the token.
	public static string SignData(SortedList<string, string> data, string token)
		// create our HMACMD5 object using the token as it's key
		HMACMD5 hmacMD5 = new HMACMD5(Encoding.UTF8.GetBytes(token));
		// stringify the data
		string toSign = "";
		foreach (KeyValuePair<string, string> kvp in data)
			toSign += kvp.Key + "=" + kvp.Value;
		// compute the hash for the stringified data and base 64 encode the hash
		byte[] hash = hmacMD5.ComputeHash(Encoding.UTF8.GetBytes(toSign));
		string signature = Convert.ToBase64String(hash);
		// remove the trailing = and return the signature
		return signature.TrimEnd('=');
	public static void Main()
		// Angelfish user account making the api request
		string username = "USERNAME";
		// the authentication token assigned to the user
		string token = "TOKEN";
		// the post data used for the api request, sorted
		SortedList<string, string> postRequestData = new SortedList<string, string>();
		postRequestData["dimensions"] = "source";
		postRequestData["metrics"] = "visits";
		postRequestData["ids"] = "1234";
		postRequestData["username"] = username;
		// add the signature to the data
		postRequestData["signature"] = SignData(postRequestData, token);
		// This is where you would use the post data for your request. For purposes
		// of this example, we simply print the signature.
Was this article helpful?
0 out of 0 found this helpful


Article is closed for comments.