comparing HMACSHA256 hash in C# for telegram login

Viewed 327

I am implementing a telegram login for a website by following the official tutorial https://core.telegram.org/widgets/login#checking-authorization

while comparing the generated hash with the one received the string is not matching.

What am I missing?

        {
            string dataCheckString =
                $"auth_date={loginData.AuthDate}\nfirst_name={loginData.FirstName}\nid={loginData.Id}\nphoto_url={loginData.PhotoUrl}\nusername={loginData.Username}";
            var secretKey = Sha256Hash("<bot_token>");

            var myHash = HashHmac(Encoding.UTF8.GetBytes(secretKey), Encoding.UTF8.GetBytes(dataCheckString));

            var myHashStr = Concat(myHash.Select(i => i.ToString("x2")));
            if (myHashStr == loginData.Hash)
            {
                // Data is from telegram
            }


            return NotFound();
        }```


    private static string Sha256Hash(string value)
    {
        using (SHA256 hash = SHA256.Create())
        {
            return Concat(hash.ComputeHash(Encoding.UTF8.GetBytes(value)).Select(i => i.ToString("x2")));
        }
    }

    private static byte[] HashHmac(byte[] key, byte[] message)
    {
        var hash = new HMACSHA256(key);
        return hash.ComputeHash(message);
    }
0 Answers
Related