C# help required to Create Facebook AppSecret_Proof HMACSHA256

社会主义新天地 提交于 2019-11-30 08:54:53
Steve

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.

Eric Kassan

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!