views:

31

answers:

1

it is September 2010 and I am trying to update Facebook connect integration on our website.

I need to validate auth cookie that was set by Facebook code. I was following PHP sample from http://developers.facebook.com/docs/guides/web

please check the C# code:

    public static Dictionary<string, string> ParseCookie(HttpCookie fbCookie)
    {
        if (fbCookie == null)
            return null;

        string value = fbCookie.Value.Substring(1, fbCookie.Value.Length - 2);
        SortedDictionary<string, string> sargs = new SortedDictionary<string, string>();

        foreach (string pair in value.Split('&'))
        {
            string[] keyvalue = pair.Split('=');
            sargs.Add(keyvalue[0], keyvalue[1]);
        }

        string sid = sargs["sig"] ?? string.Empty;
        sargs.Remove("sig");

        string payload = string.Empty;
        foreach (KeyValuePair<string, string> pair in sargs)
        {
            payload += pair.Key + "=" + pair.Value;
        }

        if (string.IsNullOrEmpty(payload) || DataFormatter.GetMD5Hash(payload + Settings.ApplicationSecret).ToUpper() != sid.ToUpper())
            return null;

        return sargs.ToDictionary(pair => pair.Key, pair => pair.Value);
    }

DataFormatter.GetMD5Hash method is:

    public static string GetMD5Hash(string key)
    {
        StringBuilder result = new StringBuilder();
        MD5 md5 = new MD5CryptoServiceProvider();
        foreach (byte b in md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)))
            result.Append(b.ToString("X2"));

        return result.ToString();
    }

The problem is that my md5 never matches sig from Facebook.

    DataFormatter.GetMD5Hash(payload + Settings.ApplicationSecret).ToUpper() != sid.ToUpper()

is always True

Please help to find the solution.

Thanks

A: 
    public static Dictionary<string, string> ParseCookie(HttpCookie fbCookie)
    {
        if (fbCookie == null)
            return null;

        string value = fbCookie.Value.Substring(1, fbCookie.Value.Length - 2);
        SortedDictionary<string, string> sargs = new SortedDictionary<string, string>();

        foreach (string pair in value.Split('&'))
        {
            string[] keyvalue = pair.Split('=');
            if (keyvalue.Length != 2)
                continue;
            sargs.Add(keyvalue[0], keyvalue[1]);
        }

        string sid = sargs["sig"] ?? string.Empty;
        sargs.Remove("sig");

        string payload = sargs.Aggregate(string.Empty, (current, pair) => current + (pair.Key + "=" + HttpUtility.UrlDecode(pair.Value)));


        if (string.IsNullOrEmpty(payload) || DataFormatter.GetMD5Hash(payload + Settings.ApplicationSecret).ToUpper() != sid.ToUpper())
            return null;

        return sargs.ToDictionary(pair => pair.Key, pair => pair.Value);
    }
Cherven