我尝试在我的项目中实现Telegram登录小部件,但遇到了问题。我不知道为什么,但我从Telegram收到的哈希值与我计算的哈希值(通过{{link1:Telegram教程}})不相等。我编写了自己的哈希计算方法,并尝试使用{{link2:Telegram登录小部件nuget包}},但两种方法都无法正常工作 :(。
我的哈希计算方法:
也许有人遇到了类似的问题?
我的哈希计算方法:
public class TelegramHmacTest
{
private const string BotToken = "123:ABC";
private const string ExpectedHash = "blablabla";
[Fact]
public void HmacTest()
{
var info = new Dictionary<string, string>
{
{"auth_date", "1234567"},
{"first_name", "abc"},
{"id", "123456"},
{"photo_url", "https://t.me/i/userpic/...jpg"},
{"username", "usr"},
};
var dataString = CombineString(info);
var computedHash = HashHMAC(dataString);
Assert.Equal(ExpectedHash, computedHash.ToLower());
}
private string HashHMAC(string message)
{
using var hasher = SHA256.Create();
var keyBytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(BotToken));
var messageBytes = Encoding.UTF8.GetBytes(message);
var hash = new HMACSHA256(keyBytes);
var computedHash = hash.ComputeHash(messageBytes);
return Convert.ToHexString(computedHash);
}
private string CombineString(IReadOnlyDictionary<string, string> meta)
{
var builder = new StringBuilder();
TryAppend("auth_date");
TryAppend("first_name");
TryAppend("id");
TryAppend("last_name");
TryAppend("photo_url");
TryAppend("username", true);
return builder.ToString();
void TryAppend(string key, bool isLast = false)
{
if (meta.ContainsKey(key))
builder.Append($"{key}={meta[key]}{(isLast ? "" : "\n")}");
}
}
}
使用库计算哈希:
[Fact]
public void TestLib()
{
var BotToken = "123:ABC";
var info = new Dictionary<string, string>
{
{"auth_date", "1234567"},
{"first_name", "abc"},
{"id", "123456"},
{"photo_url", "https://t.me/i/userpic/...jpg"},
{"username", "usr"},
};
var loginWidget = new LoginWidget(BotToken);
if (loginWidget.CheckAuthorization(info) == Authorization.Valid)
{
// user valid
}
}
也许有人遇到了类似的问题?