2013-07-15 93 views
0

我一直在试图按如下方式产生的API请求认证:BASE64(SHA256(有效载荷+秘密))API请求认证

我一直在使用下面的代码,但以base64字符串的被生成是不正确的。

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
NSString *data = @"{" 
    @"\"testing\":{" 
    @"\"uri\":\"https://example.com/something.php\"," 
    @"\"id\":\"0\"" 
    @"}" 
    @"}"; 
NSString *key = @"secret"; 
NSString *hashString = [NSString stringWithFormat:@"%@%@",data,key]; 
const char *cKey = [hashString cStringUsingEncoding:NSUTF8StringEncoding]; 
NSData *sdata = [NSData dataWithBytes:cKey length:hashString.length]; 
unsigned char sHMAC[64]; 
CC_SHA256((__bridge const void *)(sdata), sdata.length, sHMAC); 
NSData *hash = [[NSData alloc] initWithBytes:sHMAC length:sizeof(sHMAC)]; 
NSString *s = [self base64forData:hash]; 
NSLog(@"Authentication: %@",s); 
} 

//Base64 encoding 
- (NSString*)base64forData:(NSData*)theData { 
const uint8_t* input = (const uint8_t*)[theData bytes]; 
NSInteger length = [theData length]; 

static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/="; 

NSMutableData* data = [NSMutableData dataWithLength:((length + 2)/3) * 4]; 
uint8_t* output = (uint8_t*)data.mutableBytes; 

NSInteger i; 
for (i=0; i < length; i += 3) { 
    NSInteger value = 0; 
    NSInteger j; 
    for (j = i; j < (i + 3); j++) { 
     value <<= 8; 

     if (j < length) { 
      value |= (0xFF & input[j]); 
     } 
    } 

    NSInteger theIndex = (i/3) * 4; 
    output[theIndex + 0] = table[(value >> 18) & 0x3F]; 
    output[theIndex + 1] = table[(value >> 12) & 0x3F]; 
    output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; 
    output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; 
} 

return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
} 

我一直在努力与这一个已经几个星期了。 谢谢你的协助!

回答

1

您的JSON字典中有一个额外的逗号。也许这是搞砸了?

此外,请注意您的hashString看起来是这样的:

{"testing":{"uri":"https://example.com/something.php","id":"0",}}secret 

是这个打算?

另外,对于您的传统c代码,它已全部完成。见例如this answer

+0

谢谢你的回答。逗号意外地放在那里。生成授权字符串的公式是base64(sha256(payload + secret))。我认为有效载荷和秘密字符串应该在散列SHA256之前合并(hashString)?然后通过base64运行哈希以获取授权字符串。 – user2253208