Skip to content

Instantly share code, notes, and snippets.

@Karthikeyan-tv
Last active January 14, 2022 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Karthikeyan-tv/54a7c2565d9b36a40e307deab5749cae to your computer and use it in GitHub Desktop.
Save Karthikeyan-tv/54a7c2565d9b36a40e307deab5749cae to your computer and use it in GitHub Desktop.
class Program
{
static void Main(string[] args)
{
string secretCode = "9tGaq1zidmxJN8Pid6IMYhHFqAUwNbu"; // secret code
var url = "https://example.com";
// Variable declaration to form the signature URL
var query = "?page=4&access=rwd&"; // Add queries that you need.
var nonce = Guid.NewGuid().ToString(); // random string - To prevent replay attacks.
double timeStamp = DateTimeToUnixTimeStamp(DateTime.UtcNow); // current time as UNIX time stamp
var expirationTime = "100"; // alive time of the token - This can be used to make the URL expire.
var userId = 1; // User ID or user email
string queryParameter = query + "nonce=" + nonce + "&user_id=" + userId + "&timestamp=" + timeStamp + "&expirationtime=" + expirationTime;
string signature = SignURL(queryParameter.ToLower(), secretCode);
string queryWithSignature = queryParameter.ToLower() + "&signature=" + signature;
var signedUrl = url + queryWithSignature;
}
static string SignURL(string message, string secretcode)
{
var encoding = new UTF8Encoding();
var keyBytes = encoding.GetBytes(secretcode);
var messageBytes = encoding.GetBytes(message);
using (var hmacsha1 = new HMACSHA256(keyBytes))
{
var hashMessage = hmacsha1.ComputeHash(messageBytes);
return Convert.ToBase64String(hashMessage);
}
}
static double DateTimeToUnixTimeStamp(DateTime dateTime)
{
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (dateTime.ToUniversalTime() - unixStart).Ticks;
return unixTimeStampInTicks / TimeSpan.TicksPerSecond;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment