Skip to content

Instantly share code, notes, and snippets.

@ernado-x
Created January 13, 2019 13:36
Show Gist options
  • Save ernado-x/6eb4c23263f602921a2765e859cc0a03 to your computer and use it in GitHub Desktop.
Save ernado-x/6eb4c23263f602921a2765e859cc0a03 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Campus.Core.Social
{
public class TelegramAuthResponse
{
public int auth_date { get; set; }
public string first_name { get; set; }
public string hash { get; set; }
public int id { get; set; }
public string photo_url { get; set; }
public string username { get; set; }
}
public class TelegramClient
{
private readonly string _botKey;
public TelegramClient(string botKey)
{
_botKey = botKey;
}
public bool CheckTelegramAuthorization(TelegramAuthResponse response)
{
var checkList = new List<string>
{
$"auth_date={response.auth_date}",
$"first_name={response.first_name}",
$"id={response.id}",
$"photo_url={response.photo_url}",
$"username={response.username}"
};
checkList.Sort();
var dataCheckString = string.Join("\n", checkList);
var secretKey = HashString(_botKey);
var hash = GetHashSha256(secretKey, dataCheckString);
return response.hash == hash;
}
private static byte[] HashString(string text) =>
new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(text));
public static string GetHashSha256(byte[] secretKey, string text)
{
var hash = new HMACSHA256(secretKey).ComputeHash(Encoding.UTF8.GetBytes(text));
return hash.Aggregate(string.Empty, (current, x) => current + $"{x:x2}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment