我一直在尝试为iOS上的Facebook签名请求生成HMAC SHA256几周。我迫切需要帮助。
Facebook签署的请求有两个部分,以句点分隔。第一部分是有效载荷的HMAC256,而第二部分是有效载荷的Base64编码串。我只能重新创建第二部分。vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsIjAiOiJwYXlsb2FkIn0
我一直在使用以下每个人都使用的代码,但它生成了不同的哈希:
#import <CommonCrypto/CommonHMAC.h>
#import "NSData+Base64.h"
+(NSString*) hmacForSecret:(NSString*)secret data:(NSString*)data {
const char *cKey = [secret cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
return [HMAC base64EncodedString];
}
根据Facebook文档: https://developers.facebook.com/docs/authentication/signed_request/
当使用“ secret ”作为密钥时,应正确输出HMAC256:
vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso
要编码的有效负载:
{
"algorithm": "HMAC-SHA256",
"0": "payload"
}
注意:您可以对已签名请求的第二部分进行Base64解码以获取此有效负载。
答案 0 :(得分:3)
问题出在Base64编码器上。它需要编码为Base64Url,请参阅: http://en.wikipedia.org/wiki/Base64#URL_applications
这是修改后的base64EncodedString类别方法:
//NSData+Base64.h
- (NSString *)base64EncodedString
{
size_t outputLength;
char *outputBuffer = NewBase64Encode([self bytes], [self length], true, &outputLength);
NSString *result = [[[NSString alloc] initWithBytes:outputBuffer length:outputLength encoding:NSASCIIStringEncoding] autorelease];
free(outputBuffer);
NSString *b64PayloadClean = [[result componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
//do URL encoding by replacing "+" and "/" to "-" and "_" respectively
b64PayloadClean = [b64PayloadClean stringByReplacingOccurrencesOfString:@"=" withString:@""];
b64PayloadClean = [b64PayloadClean stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
b64PayloadClean = [b64PayloadClean stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
return b64PayloadClean;
}