Developing with Facebook: Signature in .NET

5. Januar 2012

At the moment I’m working a little on developing an application for Facebook. On the one hand this is for getting experience with the Facebook-API for future options in our software and on the other hand it is useful for my private life to get a glimpse at the data Facebook provides the application hoster.

First before really getting into the Facebook-API you’ll need a server which ideally supports SSL. A small test-web-application could easily be created, the IIS configured and the app registered at Facebook. Next step was to register the newly created app to the page I’m working with where my private account is the administrator.

After all the setup steps (easily described in the Facebook tutorial) and manually hacking around with Try&Error where the tutorial misses some small information, I finally got my first Facebook-data-string.

The string consists of two Base64-encoded substrings with a ‘.’ as seperator. The first is a signature of the second one – the second one is the interesting data as a JSON-array.

It’s really easy to get the data – but what worth is it without checking whether it is correct or not? So I needed to calculate the hash of the data. Sounds easy, eh? From the tutorial I knew that it is simply a HMCA SHA-256 hash-function – fortunately with a .NET equivalent.

Unfortunately getting this running was not as easy as it looked in the tutorial: After some more Try & Error I found that Facebook does not really delivers a standard Base64 string – it simply removes all ‘=’ (equivalent for String.Empty) and replaces ‘+’ with ‘-‘ and ‘/’ with ‘_’.

So after calculating the hash-value all I needed to to is to do the same as Facebook – et voilá my signature was the same.

Following is an example code how I implemented the hash-function:

Public Shared Function FacebookHMACSHA256(ByVal myKey As String, ByVal stringToHash As String) As String
Dim encoding As New System.Text.ASCIIEncoding
Dim key() As Byte = encoding.GetBytes(myKey)
Dim XML() As Byte = encoding.GetBytes(stringToHash)
Dim myHMACSHA256 As New System.Security.Cryptography.HMACSHA256(key)
Dim HashCode As Byte() = myHMACSHA256.ComputeHash(XML)
Dim output As String = ToUrlBase64String(myHMACSHA256.Hash)

Return output
End Function

Shared Function ToUrlBase64String(ByVal input As Byte()) As String
' Facebook benutzt andere URL-Encoding-Zeichen
Return Convert.ToBase64String(input).Replace("=", String.Empty).Replace("+", "-").Replace("/", "_")
End Function

Finally it’s worth to say that the first glimpse at the data Facebook supports is really really interesting. Soon I will report about my next experience with this experiment.