C# URI Hash Link Generation Sample Script

Plain HTML / Printer friendly.Plain HTML / Printer friendly.

 

Sample script to generate the URI hash link using the C# programming language...

using System;
using System.Security.Cryptography;
using System.Text;

MD5 md5Hasher = MD5.Create();
byte[] hash;
string keyStr;
string base64;
double timestamp;

# Inputs from user
string secret; # secret key
string uri; # request uri , example /images/dotnet.jpg
DateTime date; # expiry datetime

keyStr = uri + secret;  
hash = md5Hasher.ComputeHash(Encoding.Default.GetBytes(keyStr));
base64 = Convert.ToBase64String(hash).Replace("+" , "-").Replace("/" , "_");
Console.WriteLine("Without timestamp");
Console.WriteLine("uri=" + uri + " ; keystr=" + keyStr + " ; urlHash=" + base64);

timestamp = Math.Round((date - new DateTime(1970,1,1,0,0,0)).TotalSeconds, 0);
keyStr = timestamp.ToString() + uri + secret;
hash = md5Hasher.ComputeHash(Encoding.Default.GetBytes(keyStr));
base64 = Convert.ToBase64String(hash).Replace("+" , "-").Replace("/" , "_");
Console.WriteLine("\nWith Timestamp for "  + date.ToString("u") + " , " + timestamp);
Console.WriteLine("uri=" + uri + " ; keystr=" + keyStr + " ; urlHash=" + base64);