Skip to content

Instantly share code, notes, and snippets.

@undrcrxwn
Created July 21, 2024 13:26
Show Gist options
  • Save undrcrxwn/140bcaccbeac31675a8966c1bc78bc79 to your computer and use it in GitHub Desktop.
Save undrcrxwn/140bcaccbeac31675a8966c1bc78bc79 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
public class HashGenerator
{
public static string GenerateHash(Dictionary<string, object> data, string botToken)
{
// Step 1: Create data_check_string
var sortedKeys = data.Keys.Where(k => k != "hash").OrderBy(k => k);
StringBuilder dataCheckStringBuilder = new StringBuilder();
foreach (var key in sortedKeys)
{
dataCheckStringBuilder.Append($"{key}={data[key]}\n");
}
string dataCheckString = dataCheckStringBuilder.ToString().TrimEnd('\n');
// Step 2: Generate secret key using SHA256
byte[] secretKey = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(botToken));
// Step 3: Compute HMAC-SHA256
using (var hmac = new HMACSHA256(secretKey))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(dataCheckString));
string computedHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
return computedHash;
}
}
}
// Example usage
class Program
{
static void Main()
{
// Sample data
var data = new Dictionary<string, object>
{
{ "id", 837151456 },
{ "first_name", "Таёжныи ишак" },
{ "username", "UNDRCRXWN" },
{ "photo_url", "https://t.me/i/userpic/320/CFg5yjsNuLaPzr9jbyeFAonIv-EpIwWu_wq6zvuK1-Y.jpg" },
{ "auth_date", 1721555915 },
{ "hash", "<to-be-computed>" }
};
// Telegram Bot API Token
string botToken = "8800712301:ABiOf-KfIAvqE139fEmcAlm3015hf3DFsC";
// Generate hash
string hashValue = HashGenerator.GenerateHash(data, botToken);
Console.WriteLine("Generated Hash: " + hashValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment