· 7 years ago · Jan 13, 2019, 08:54 PM
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Security.Cryptography;
5using System.Text;
6
7namespace Campus.Core.Social
8{
9 public class TelegramAuthResponse
10 {
11 public int auth_date { get; set; }
12 public string first_name { get; set; }
13 public string hash { get; set; }
14 public int id { get; set; }
15 public string photo_url { get; set; }
16 public string username { get; set; }
17 }
18
19 public class TelegramClient
20 {
21 private readonly string _botKey;
22
23 public TelegramClient(string botKey)
24 {
25 _botKey = botKey;
26 }
27
28 public bool CheckTelegramAuthorization(TelegramAuthResponse response)
29 {
30 var checkList = new List<string>
31 {
32 $"auth_date={response.auth_date}",
33 $"first_name={response.first_name}",
34 $"id={response.id}",
35 $"photo_url={response.photo_url}",
36 $"username={response.username}"
37 };
38
39 checkList.Sort();
40
41 var dataCheckString = string.Join("\n", checkList);
42
43 var secretKey = HashString(_botKey);
44 var hash = GetHashSha256(secretKey, dataCheckString);
45
46 return response.hash == hash;
47 }
48
49 private static byte[] HashString(string text) =>
50 new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(text));
51
52
53
54 public static string GetHashSha256(byte[] secretKey, string text)
55 {
56 var hash = new HMACSHA256(secretKey).ComputeHash(Encoding.UTF8.GetBytes(text));
57 return hash.Aggregate(string.Empty, (current, x) => current + $"{x:x2}");
58 }
59 }
60}