Last active
June 20, 2025 20:13
-
-
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 hidden or 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 = Convert.ToHexStringLower(hashBytes); | |
return computedHash.Equals(hash); | |
} |
Hi. Have you checked to see if this code works? I've been struggling with this problem for two days now, but my hashes don't want to match(
Hi, I have updated the code (no logic was changed) - the code is working nonetheless. Make sure your initData and botToken are correct.
Or you can try installing this Nuget and using AuthHelpers.ParseValidateData static function to validate the data.
Thank you so much. This is a very helpful code. 💪
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. Have you checked to see if this code works? I've been struggling with this problem for two days now, but my hashes don't want to match(