gpt4 book ai didi

c# - Facebook Webhook签名计算(C#)

转载 作者:行者123 更新时间:2023-12-03 19:34:43 30 4
gpt4 key购买 nike

Facebook Webhooks为每次调用提供签名以验证有效负载的完整性和来源,但对我而言,它描述得很差(Facebook Webhook Reference - Security)。因此,我在计算签名以验证它时遇到了一些麻烦。那么,计算值的步骤是什么?

最佳答案

我可以使用它,并希望在这里与其他开发人员共享我的解决方案(使用C#):

    /// <summary>
/// The HTTP request will contain an X-Hub-Signature header which contains the SHA1 signature of the request payload,
/// using the app secret as the key, and prefixed with sha1=.
/// Your callback endpoint can verify this signature to validate the integrity and origin of the payload
/// </summary>
/// <param name="appSecret">facebook app secret</param>
/// <param name="payload">body of webhook post request</param>
/// <returns>calculated signature</returns>
public static string CalculateSignature(string appSecret, string payload)
{
/*
Please note that the calculation is made on the escaped unicode version of the payload, with lower case hex digits.
If you just calculate against the decoded bytes, you will end up with a different signature.
For example, the string äöå should be escaped to \u00e4\u00f6\u00e5.
*/
payload = EncodeNonAsciiCharacters(payload);

byte[] secretKey = Encoding.UTF8.GetBytes(appSecret);
HMACSHA1 hmac = new HMACSHA1(secretKey);
hmac.Initialize();
byte[] bytes = Encoding.UTF8.GetBytes(payload);
byte[] rawHmac = hmac.ComputeHash(bytes);

return ByteArrayToString(rawHmac).ToLower();
}

private static string EncodeNonAsciiCharacters(string value)
{
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
if (c > 127)
{
string encodedValue = "\\u" + ((int)c).ToString("x4");
sb.Append(encodedValue);
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}

private static string ByteArrayToString(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-", "");
}

关于c# - Facebook Webhook签名计算(C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38353831/

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