如何在Objective-C中解码已签名的请求?
基本上,我如何将这个Ruby代码翻译成Objective-C或C?
# Facebook sends a signed_requests to authenticate certain requests.
# http://developers.facebook.com/docs/authentication/signed_request/
def decode_signed_request(signed_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看起来很有帮助。
答案 0 :(得分:1)
您想验证数据上的签名还是只是“解码”它?如果是后者,您可以忽略签名:
NSString *signedData = ...;
NSString *base64EncodedData = [[signedData componentsSeparatedByString:@"."] objectAtIndex:1];
NSString *jsonString = [NSString stringWithBase64String:base64EncodedData];
id jsonObject = ...;
我使用Facebook SDK并选择合适的JSON框架(我建议JSONKit)由你决定。
您的评论表明您要验证消息中包含的HMAC。在那种情况下:
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