gpt4 book ai didi

c# - Facebook实时更新: Validating X-Hub-Signature SHA1 signature in C#

转载 作者:太空宇宙 更新时间:2023-11-03 17:45:54 26 4
gpt4 key购买 nike

当 Facebook 发送实时更新时,它们会在 HTTP header 中包含 X-Hub-Signature。根据他们的文档(http://developers.facebook.com/docs/api/realtime),他们使用 SHA1 和应用程序 key 作为 key 。我试图验证这样的签名:

public void MyAction() {
string signature = request.Headers["X-Hub-Signature"];
request.InputStream.Position = 0;
StreamReader reader = new StreamReader(request.InputStream);
string json = reader.ReadToEnd();

var hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(json), UTF8Encoding.UTF8.GetBytes("MySecret"));
var hmacBase64 = ToUrlBase64String(hmac);

bool isValid = signature.Split('=')[1] == hmacBase64;

}


private static byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody) {
using (var hmacAlgorithm = new System.Security.Cryptography.HMACSHA1(keyBody)) {
hmacAlgorithm.ComputeHash(dataToSign);
return hmacAlgorithm.Hash;
}
}

private static string ToUrlBase64String(byte[] Input) {
return Convert.ToBase64String(Input).Replace("=", String.Empty)
.Replace('+', '-')
.Replace('/', '_');
}

但我似乎无法验证这一点。对我做错了什么有任何想法吗?

提前致谢。

最佳答案

如果有人需要此信息:

开尔文提供的可能会奏效,但看起来很麻烦。
您只需要使用 ConvertToHexadecimal 函数,而不是使用 ToUrlBase64String 函数。

请参阅下面的完全更新的代码:

public void MyAction() {
string signature = request.Headers["X-Hub-Signature"];
request.InputStream.Position = 0;
StreamReader reader = new StreamReader(request.InputStream);
string json = reader.ReadToEnd();

var hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(json), UTF8Encoding.UTF8.GetBytes("MySecret"));
var hmacHex = ConvertToHexadecimal(hmac);

bool isValid = signature.Split('=')[1] == hmacHex ;

}


private static byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody) {
using (var hmacAlgorithm = new System.Security.Cryptography.HMACSHA1(keyBody)) {
return hmacAlgorithm.ComputeHash(dataToSign);
}
}

private static string ConvertToHexadecimal(IEnumerable<byte> bytes)
{
var builder = new StringBuilder();
foreach (var b in bytes)
{
builder.Append(b.ToString("x2"));
}

return builder.ToString();
}

关于c# - Facebook实时更新: Validating X-Hub-Signature SHA1 signature in C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390543/

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