gpt4 book ai didi

C# 检查 Telegram 登录 hmac

转载 作者:行者123 更新时间:2023-12-05 04:27:03 25 4
gpt4 key购买 nike

我尝试在我的项目中实现 Telegram 登录小部件,但遇到了问题。我不知道为什么,但是我从 Telegram 中收到的哈希和我计算的哈希(由 tutorial from telegram )不相等。我写了我自己的哈希计算方法,并尝试使用 telegram login widget nuget package 但两种方法都不起作用:(。

我的哈希计算方法:

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
}
}

也许有人遇到过类似的问题?

最佳答案

问题出在我没有在 BotFather 中注册域名。在 Telegram 登录小部件文档中,没有关于您必须在 BotFather 中为您的机器人注册域的信息。我还发现您只能注册 https 域和 '127.0.0.1' 进行测试。

关于C# 检查 Telegram 登录 hmac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72904483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com