Using C#, how can one verify the Telegram bot hash from login parameters? Below is a revised code example that sorts parameters, decodes URLs, and compares HMAC-SHA256 hashes.
public IActionResult VerifyTelegramLogin([FromQuery] Dictionary<string, string> entries)
{
if (!entries.TryGetValue("signature", out string receivedSig) || string.IsNullOrWhiteSpace(receivedSig))
return BadRequest("Signature not provided");
entries.Remove("signature");
if (entries.ContainsKey("avatar_url"))
entries["avatar_url"] = WebUtility.UrlDecode(entries["avatar_url"]);
string sortedData = string.Join("\n", entries.OrderBy(pair => pair.Key)
.Select(pair => $"{pair.Key}:{pair.Value}"));
byte[] keyHash = GenerateSHA256("YourBotTokenHere");
byte[] computedSig = CreateHMAC(keyHash, Encoding.UTF8.GetBytes(sortedData));
string computedSigStr = string.Concat(computedSig.Select(b => b.ToString("x2")));
return computedSigStr == receivedSig ? Ok("Verified") : Unauthorized("Invalid signature");
}
private static byte[] GenerateSHA256(string input)
{
using (SHA256 sha = SHA256.Create())
return sha.ComputeHash(Encoding.UTF8.GetBytes(input));
}
private static byte[] CreateHMAC(byte[] key, byte[] data)
{
using (HMACSHA256 hmac = new HMACSHA256(key))
return hmac.ComputeHash(data);
}