创建Facebook AppSecret_Proof HMACSHA256需要C#帮助

Facebook要求我创建appsecret_proof: https : //developers.facebook.com/docs/graph-api/securing-requests

我使用以下代码完成了此操作:

public string FaceBookSecret(string content, string key) { var encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(key); byte[] messageBytes = encoding.GetBytes(content); using (var hmacsha256 = new HMACSHA256(keyByte)) { byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); return Convert.ToBase64String(hashmessage); } } 

一切看起来都不错,但facebook说appsecret_proof无效。 我已登录,当我删除密钥时,我可以正常地完成所有操作。 所以要节省一些时间:

  • 是的我发布到正确的URL
  • 是的我传递了一个有效的access_token
  • 是的我在certificate中使用相同的access_token,就像我在请求中一样
  • 是的,我的appsecret很好,并且有效

使用示例

 dynamic results = client.Post("/" + model.PostAsId + "/feed", new { message = model.Message, appsecret_proof = FaceBookSecret(postAs.AuthToken, AppSecret) }); 

我认为它可能与编码或其他东西有关,但说实话,我只是不知道。

我也在使用Facebook .net SDK,但这在文档中没有多少,并且似乎没有涉及与自动化,服务器端操作等有关的任何事情。

谢谢

app secret是一个base-16字符串,因此您需要将其转换为字节数组。 看一下如何将hex字符串转换为字节数组? 有关如何执行此操作的详细信息。 需要使用ASCII编码将access_token转换为字节数组。 生成HMAC后,将其编码为base-16字符串,以用作appsecret_proof。 以下代码将字节数组转换为base16。

 public static class Base16 { private static readonly char[] encoding; static Base16() { encoding = new char[16] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; } public static string Encode(byte[] data) { char[] text = new char[data.Length * 2]; for (int i = 0, j = 0; i < data.Length; i++) { text[j++] = encoding[data[i] >> 4]; text[j++] = encoding[data[i] & 0xf]; } return new string(text); } } 

然后生成appsecret_proof的代码将是

 private string GenerateAppSecretProof(string accessToken, string appSecret) { byte[] key = Base16.Decode(appSecret); byte[] hash; using (HMAC hmacAlg = new HMACSHA1(key)) { hash = hmacAlg.ComputeHash(Encoding.ASCII.GetBytes(accessToken)); } return Base16.Encode(hash); } 

Facebook似乎接受SHA256 HMACSHA1 HMAC

我在Facebook上成功使用了以下内容

 using System.Security.Cryptography; using System.Text; internal static string FaceBookSecret(string content, string key) { byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] messageBytes = Encoding.UTF8.GetBytes(content); byte[] hash; using (HMACSHA256 hmacsha256 = new HMACSHA256(keyBytes)) { hash = hmacsha256.ComputeHash(messageBytes); } StringBuilder sbHash = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sbHash.Append(hash[i].ToString("x2")); } return sbHash.ToString(); }