Skip to content

Instantly share code, notes, and snippets.

@ReubenBond
Last active August 29, 2015 14:05
Show Gist options
  • Save ReubenBond/d6de67600f2fa735dbfa to your computer and use it in GitHub Desktop.
Save ReubenBond/d6de67600f2fa735dbfa to your computer and use it in GitHub Desktop.
Azure DocumentDB: Compute Signature
public static string GetSignature(string masterKey, string resourceId, string resourceType, string xDate = null, string date = null)
{
if (string.IsNullOrEmpty(xDate) && string.IsNullOrEmpty(date))
{
throw new ArgumentException("Either xDate or date must be provided.");
}
const string AuthorizationFormat = "type={0}&ver={1}&sig={2}";
const string MasterToken = "master";
const string TokenVersion = "1.0";
var masterKeyBytes = Convert.FromBase64String(masterKey);
var hmacSha256 = new HMACSHA256(masterKeyBytes);
var resourceIdInput = resourceId ?? string.Empty;
var resourceTypeInput = resourceType ?? string.Empty;
if (string.IsNullOrEmpty(xDate)) {
date.ToLowerInvariant();
} else {
date = string.Empty;
}
var payLoad = string.Format(CultureInfo.InvariantCulture,
"{0}\n{1}\n{2}\n{3}\n{4}\n",
"GET".ToLowerInvariant(),
resourceTypeInput.ToLowerInvariant(),
resourceIdInput.ToLowerInvariant(),
(xDate ?? string.Empty).ToLowerInvariant(),
date);
var hashPayLoad = hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(payLoad));
var authorizationToken = Convert.ToBase64String(hashPayLoad);
return System.Web.HttpUtility.UrlEncode(string.Format(
CultureInfo.InvariantCulture,
AuthorizationFormat,
MasterToken,
TokenVersion,
authorizationToken));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment