-
-
Save aciudacov/1279d1b9fde512ac34aa7cded5865f2b to your computer and use it in GitHub Desktop.
| 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. 💪
Hi! There's a problem with this gist: slashes in the profile photo URL cause a mismatch in hashes.
We should change:
var checkString = string.Join("\n", data.AllKeys.OrderBy(key => key).Select(key => $"{key}={data[key]}"));
to:
var checkString = string.Join("\n", data.AllKeys.OrderBy(key => key).Select(key => $"{key}={data[key]?.Replace("/", "\\/")}"));
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(