Skip to content

Instantly share code, notes, and snippets.

@MihaZupan
Last active July 25, 2018 11:25
Show Gist options
  • Save MihaZupan/0d0a836c1fdb1c2dd983c88b8736ea5d to your computer and use it in GitHub Desktop.
Save MihaZupan/0d0a836c1fdb1c2dd983c88b8736ea5d to your computer and use it in GitHub Desktop.
// using System;
// using System.Text;
// using System.Security.Cryptography;
static bool CheckAuthorization(Dictionary<string, string> fields, string token, string hash)
{
int allowedTimeOffset = 30; // Or whatever you choose
if (!fields.ContainsKey("auth_date")) return false;
if (long.TryParse(fields["auth_date"], out long timestamp))
{
if (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds - timestamp > allowedTimeOffset)
return false;
}
else return false;
var sortedFields = fields.OrderBy(i => i.Key).ToArray();
StringBuilder data_check_string = new StringBuilder();
for (int i = 0; i < sortedFields.Length; i++)
{
data_check_string.Append(sortedFields[i].Key);
data_check_string.Append('=');
data_check_string.Append(sortedFields[i].Value);
if (i != sortedFields.Length - 1)
{
data_check_string.Append('\n');
}
}
using (HMACSHA256 hmac = new HMACSHA256())
{
using (SHA256 sha256 = SHA256.Create())
{
hmac.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(token));
}
byte[] signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(data_check_string.ToString()));
string hexSignature = BitConverter.ToString(signature).Replace("-", "");
return hexSignature == hash.ToUpper();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment