开发者

Objective-C: Decode Signed Request

开发者 https://www.devze.com 2023-03-28 05:57 出处:网络
How do I decode a signed request in Objective-C? Basically, how do I translate this Ruby code to Objective-C or C?

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

精彩评论

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