开发者

Objective-C: Decode Signed Request

How do I decode a signed request in Objective-C?

Basically, how do I translate this Ruby code to Objective-C or C?

# Facebook sends a signed_requests to authenticate certain requests.
# http://developers.facebook.com/docs/authentication/signed_request/
def decode_signed_request(signe开发者_开发百科d_request)
  encoded_signature, encoded_data = signed_request.split('.')
  signature = base64_url_decode(encoded_signature)
  expected_signature = OpenSSL::HMAC.digest('sha256', @secret, encoded_data)
  if signature == expected_signature
    JSON.parse base64_url_decode(encoded_data)
  end
rescue Exception => e
  puts $!, $@
end

def base64_url_decode(string)
  "#{string}==".tr("-_", "+/").unpack("m")[0]
end

SSToolKit Base64 decode NSString looks helpful.


Do you want to verify the signature on the data or just "decode" it? If it's the latter, you can just ignore the signature:

NSString *signedData = ...;
NSString *base64EncodedData = [[signedData componentsSeparatedByString:@"."] objectAtIndex:1];
NSString *jsonString = [NSString stringWithBase64String:base64EncodedData];
id jsonObject = ...;

I leave using the Facebook SDK and choosing a suitable JSON framework (I recommend JSONKit) up to you.

Your comment indicates that you want to verify the HMAC included with the message. In that case:

unsigned int length = 0;
unsigned char *expectedHmac = HMAC(EVP_sha256(), [key bytes], [key length], [base64EncodedData UTF8String], [base64EncodedData length], NULL, &length);
NSData *expectedHmacData = [NSData dataWithBytes:expectedHmac length:length];
// compare expected hmac
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜