Last active
June 19, 2024 13:20
-
-
Save aciudacov/1279d1b9fde512ac34aa7cded5865f2b to your computer and use it in GitHub Desktop.
Telegram Web App Bot data validation (initData) in .NET/C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Specialized; | |
using System.Security.Cryptography; | |
using System.Text; | |
using System.Web; | |
/// <summary> | |
/// Validates init data passed to Telegram WebApp. | |
/// </summary> | |
/// <param name="initData"> | |
/// String received from Telegram WebApp. Accessible via Telegram.WebApp.initData on the web. | |
/// </param> | |
/// <param name="botToken"> | |
/// Current token of the bot that was used to open WebApp. | |
/// </param> | |
/// <returns> | |
/// True if data is valid, otherwise false. | |
/// </returns> | |
public static bool ValidateInitData(string initData, string botToken) | |
{ | |
NameValueCollection data = HttpUtility.ParseQueryString(initData); | |
var hash = data["hash"]; | |
data.Remove("hash"); | |
var checkString = string.Join("\n", data.AllKeys.OrderBy(key => key).Select(key => $"{key}={data[key]}")); | |
var hmacKey = new HMACSHA256(Encoding.UTF8.GetBytes("WebAppData")); | |
var secretKey = hmacKey.ComputeHash(Encoding.UTF8.GetBytes(botToken)); | |
var hashKey = new HMACSHA256(secretKey); | |
var hashBytes = hashKey.ComputeHash(Encoding.UTF8.GetBytes(checkString)); | |
var computedHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); | |
return computedHash.Equals(hash); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment