18

I thought I would try and get the new Signed Request logic added to my facebook canvas application, to make this "easy" on myself I went to the facebook PHP sdk over at GitHub and took a look at the unit tests.

My actual problem is that I cannot get the hash included in the request to match the hash I calculate using the application secret, and the data sent within the request.

How this is meant to work is described at Facebook's authentication page.

private string VALID_SIGNED_REQUEST = "ZcZocIFknCpcTLhwsRwwH5nL6oq7OmKWJx41xRTi59E.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOiIxMjczMzU5NjAwIiwib2F1dGhfdG9rZW4iOiIyNTQ3NTIwNzMxNTJ8Mi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODV8dUk3R3dybUJVZWQ4c2VaWjA1SmJkekdGVXBrLiIsInNlc3Npb25fa2V5IjoiMi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODUiLCJ1c2VyX2lkIjoiMTY3Nzg0NjM4NSJ9";

private string NON_TOSSED_SIGNED_REQUEST = "laEjO-az9kzgFOUldy1G7EyaP6tMQEsbFIDrB1RUamE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiJ9";

public void SignedRequestExample()
{
 var Encoding = new UTF8Encoding();

 string ApplicationSecret = "904270b68a2cc3d54485323652da4d14"; 

 string SignedRequest = VALID_SIGNED_REQUEST;
 string ExpectedSignature = SignedRequest.Substring(0, SignedRequest.IndexOf('.'));
 string Payload = SignedRequest.Substring(SignedRequest.IndexOf('.') + 1);

 // Back & Forth with Signature
 byte[] ActualSignature = FromUrlBase64String(ExpectedSignature);
 string TestSignature = ToUrlBase64String(ActualSignature);

 // Back & Forth With Data
 byte[] ActualPayload = FromUrlBase64String(Payload);
 string Json = Encoding.GetString(ActualPayload);
 string TestPayload = ToUrlBase64String(ActualPayload);

 // Attempt to get same hash
 var Hmac = SignWithHMAC(ActualPayload, Encoding.GetBytes(ApplicationSecret));
 var HmacBase64 = ToUrlBase64String(Hmac);            
 var HmacHex = BytesToHex(Hmac);

 if (HmacBase64 != ExpectedSignature)
 {
  // YAY
 }
 else
 {
  // BOO
 }
}

private static string BytesToHex(byte[] input)
{
 StringBuilder sb = new StringBuilder();

 foreach (byte b in input)
 {
  sb.Append(string.Format("{0:x2}", b));
 }
 return sb.ToString();
}
private string ToUrlBase64String(byte[] Input)
{
 return Convert.ToBase64String(Input).Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
}

// http://tools.ietf.org/html/rfc4648#section-5            
private byte[] FromUrlBase64String(string Base64UrlSafe)
{
 Base64UrlSafe = Base64UrlSafe.PadRight(Base64UrlSafe.Length + (4 - Base64UrlSafe.Length % 4) % 4, '=');
 Base64UrlSafe = Base64UrlSafe.Replace('-', '+').Replace('_', '/');
 return Convert.FromBase64String(Base64UrlSafe);
}

private byte[] SignWithHMAC(byte[] dataToSign, byte[] keyBody)
{
 using (var hmac = new HMACSHA256(keyBody))
 {
  hmac.ComputeHash(dataToSign);
  /*
  CryptoStream cs = new CryptoStream(System.IO.Stream.Null, hmac, CryptoStreamMode.Write);
  cs.Write(dataToSign, 0, dataToSign.Length);
  cs.Flush();
  cs.Close();
  byte[] hashResult = hmac.Hash;
  */
  return hmac.Hash;
 }
}

public string Base64ToHex(string input)
{
 StringBuilder sb = new StringBuilder();
 byte[] inputBytes = Convert.FromBase64String(input);
 foreach (byte b in inputBytes)
 {
  sb.Append(string.Format("{0:x2}", b));
 }
 return sb.ToString();
}

Answer thanks to Rasmus below, to assist anyone else here is the updated (cleaned up code):

/// Example signed_request variable from PHPSDK Unit Testing
private string VALID_SIGNED_REQUEST = "ZcZocIFknCpcTLhwsRwwH5nL6oq7OmKWJx41xRTi59E.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOiIxMjczMzU5NjAwIiwib2F1dGhfdG9rZW4iOiIyNTQ3NTIwNzMxNTJ8Mi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODV8dUk3R3dybUJVZWQ4c2VaWjA1SmJkekdGVXBrLiIsInNlc3Npb25fa2V5IjoiMi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODUiLCJ1c2VyX2lkIjoiMTY3Nzg0NjM4NSJ9";

public bool ValidateSignedRequest()
{            
    string applicationSecret = "904270b68a2cc3d54485323652da4d14";
    string[] signedRequest = VALID_SIGNED_REQUEST.Split('.');            
    string expectedSignature = signedRequest[0];
    string payload = signedRequest[1];

    // Attempt to get same hash
    var Hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(payload), UTF8Encoding.UTF8.GetBytes(applicationSecret));
    var HmacBase64 = ToUrlBase64String(Hmac);

    return (HmacBase64 == expectedSignature);           
}


private string ToUrlBase64String(byte[] Input)
{
    return Convert.ToBase64String(Input).Replace("=", String.Empty)
                                        .Replace('+', '-')
                                        .Replace('/', '_');
}

private byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
{
    using (var hmacAlgorithm = new HMACSHA256(keyBody))
    {
        hmacAlgorithm.ComputeHash(dataToSign);
        return hmacAlgorithm.Hash;
    }
}
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • 1
    I'm going to go out on a limb here and say you're a C/C++ coder who barely knows any C#. – Steven Sudit Aug 02 '10 at 07:24
  • Hi Steven, not so new, just got myself into a bad place today. Thought the collective minds of stack overflow could get me out. – CameraSchoolDropout Aug 02 '10 at 09:23
  • Don't you mean `return (HmacBase64 == expectedSignature);` ? I would expect the method to return true if the signature was correct. – Rasmus Faber Aug 02 '10 at 10:03
  • Sure did - thanks again Rasmus! – CameraSchoolDropout Aug 02 '10 at 12:28
  • What I meant is that the code is not idiomatic C#, and that can hide a whole bunch of defects. To make much headway, I'd have to start by cleaning it up, as Rasmus did, but perhaps more thoroughly. – Steven Sudit Aug 02 '10 at 13:24
  • How did you actually decode the payload to json object? What's the equivalent to PHP code $data = json_decode(base64_url_decode($payload), true); – cdpnet Aug 12 '10 at 23:03
  • If that's a real secret key, you should generate a new one now. Secret keys shouldn't be shared publicly. – DuckMaestro Jun 28 '11 at 03:45
  • @DuckMaestro Thanks for sharing the concern - the internet now owes you some security karma! The secret key is from the facebook github repo, it's the same one published in their PHP example :) Thanks again tho! – CameraSchoolDropout Jun 28 '11 at 11:24
  • Cleaned up version works a treat - cheers! – stephen Jul 14 '11 at 13:13

2 Answers2

17

You are not supposed to base64-decode the payload before calculating the HMAC.

Use this line:

var Hmac = SignWithHMAC(Encoding.GetBytes(Payload), Encoding.GetBytes(ApplicationSecret));

and it should work.

A few more pointers:

  • Instead of fiddling with Substring() and IndexOf() try using String.Split()
  • You have switched the YAY and BOO comments around
  • C# code is more readable if you follow the common rule of starting the names of local variables with lowercase (like this: var applicationSecret = "...";)
Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189
  • Thanks Rasmus - appreciate your help! – CameraSchoolDropout Aug 02 '10 at 09:10
  • If you dont want to do this all yourself just use the Facebook .Net SDK on Codeplex. It will handled signed request for you. http://facebooksdk.codeplex.com – Nate Totten Sep 19 '10 at 22:10
  • @NathanTotten could you please tell me which class.method to use for generating the hash, I have the secret and key and I need the hash generated ? – Omu Apr 20 '12 at 13:13
0

Thank, James! Your code helped me a lot.

cdpnet, add like Newtonsoft.Json to your project, and then it's this:

        JObject UnencodedPayload = JObject.Parse(Encoding.GetString(ActualPayload));

-Kevin

kevin
  • 417
  • 4
  • 20