2016-07-13 55 views
2

Facebook Webhooks为每次调用提供了一个签名来验证有效负载的完整性和来源,但对我来说这是不好描述(Facebook Webhook Reference - Security)。正因为如此,我在计算签名来验证它时遇到了一些麻烦。那么计算价值的步骤是什么?facebook webhook签名计算(C#)

+0

共享是伟大的,但你要坚持到问题的SO“格式” - >答案(S )。因此,请将您的问题编辑为描述问题的内容,然后将自己的解决方案作为自己的答案发布。 http://stackoverflow.com/help/self-answer – CBroe

+1

@CBroe我为此道歉。我已经修好了。谢谢。 – TomPez

回答

3

我得到它的工作,并希望分享我对其他开发人员在这里解决方案(在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("-", ""); 
    }