Skip to content

Instantly share code, notes, and snippets.

@cairey
Created August 25, 2015 14:42
Show Gist options
  • Save cairey/fb5dd88838b57ca27107 to your computer and use it in GitHub Desktop.
Save cairey/fb5dd88838b57ca27107 to your computer and use it in GitHub Desktop.
Hashed URL
public class HashedUrl
{
private readonly string _secretKey;
private readonly string _urlToHash;
private readonly DateTime _startDate;
private readonly DateTime _endDate;
/// <summary>
/// Hash a url
/// </summary>
/// <param name="secretKey"> Example: 98uekjfbnw</param>
/// <param name="urlToHash">Example: http://cdn.com/client/PRCR_1MBPS.mp4 This Url is case sensitive</param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
public HashedUrl(string secretKey, string urlToHash, DateTime startDate, DateTime endDate)
{
_secretKey = secretKey;
_urlToHash = urlToHash;
_startDate = startDate;
_endDate = endDate;
}
public string Generate()
{
var uri = new Uri(_urlToHash, UriKind.Absolute);
var pathAndQuery = uri.PathAndQuery;
var choppedLeftPartUrl = uri.ToString().Replace(pathAndQuery, "");
var combinedWithParams = pathAndQuery + "?s=" + _startDate.ToString("yyyyMMddHHmmss") + "&" + "e=" + _endDate.ToString("yyyyMMddHHmmss");
var hash = CalculateSHA1(combinedWithParams, _secretKey);
var newPathAndQuery = combinedWithParams + "&hash=0" + hash.Substring(0, 20);
return choppedLeftPartUrl + newPathAndQuery;
}
public static string CalculateSHA1(string text, string secretKey)
{
var textBytes = Encoding.ASCII.GetBytes(text);
var secretKeyBytes = Encoding.ASCII.GetBytes(secretKey);
var hmacSHA1 = new HMACSHA1(secretKeyBytes);
var saltedHash = hmacSHA1.ComputeHash(textBytes);
var result = ByteToString(saltedHash);
return result.ToLower();
}
public static string ByteToString(byte[] buff)
{
var sbinary = "";
for(var i = 0; i < buff.Length; i++)
{
sbinary += buff[i].ToString("X2"); // hex format
}
return (sbinary);
}
}
var hashedUrl = new HashedUrl("98uekjfbnw", "http://cdn.com/client/PRCR_1MBPS.mp4", DateTime.Now, DateTime.Now.AddDays(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment