C# help required to Create Facebook AppSecret_Proof HMACSHA256

后端 未结 2 461
梦如初夏
梦如初夏 2020-12-31 11:51

Facebook requires that I create a appsecret_proof: https://developers.facebook.com/docs/graph-api/securing-requests

And I have done this using the following code:<

相关标签:
2条回答
  • 2020-12-31 12:11

    I have used the below successfully with 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();
    }
    
    0 讨论(0)
  • 2020-12-31 12:23

    The app secret is a base-16 string, so you need to convert that to a byte array. Take a look at How can I convert a hex string to a byte array? for details on how to do this. The access_token needs to be converted to a byte array using the ASCII encoding. Once you've generated the HMAC then encode this as a base-16 string to use as your appsecret_proof. The following code will convert a byte array to 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);
        }
    }
    

    The code to generate the appsecret_proof would then be

    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 seems to accept either a SHA256 HMAC or SHA1 HMAC.

    0 讨论(0)
提交回复
热议问题