php到iphone代码 - CCHmac kCCHmacAlgSHA256

时间:2011-04-19 03:53:47

标签: iphone objective-c restful-authentication hmac sha256

我正在尝试使用hmac sha256加密登录我的服务器,我在php中有工作代码,但是无法让它在iphone中运行并追踪到iphone中的hmac产生不同的输出到php代码,给出相同的投入 php代码是

  $privatekey = '6-y6f"\%BjSM;HBo\'sPr")5#t2nb-LG*;])f^Si[';
  $identity_arrow_getSecret = $privatekey;
  $date_c = "2011-04-18T23:56:28+0800";
  $uri = '/backend/1/User/Header';

  $stringToSign =  "GET\n\n\n" . $date_c . "\n" . $uri;
  $signature = hash_hmac("sha256", utf8_encode($stringToSign), $identity_arrow_getSecret);
  echo "stringToSign is $stringToSign <HR>";
  echo "signature is $signature <HR>";

objective-c代码是

NSString* uri = @"/backend/1/User/Header";
NSString* date_c = @"2011-04-18T23:56:28+0800"; //[dateFormatter stringFromDate:[NSDate date]];
NSString* stringToSign = [NSString stringWithFormat:@"GET\n\n\n%@\n%@" , date_c , uri];
NSLog(@" stringToSign : %@ <>\r\n", stringToSign);

NSString* privatekey = @"6-y6f\"\%BjSM;HBo\'sPr\")5#t2nb-LG*;])f^Si[";

const char *cKey  = [privatekey cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [stringToSign cStringUsingEncoding:NSASCIIStringEncoding];

unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

NSString *hash = [HMAC base64EncodedString];
NSLog(@" hash : %@ \r\n", hash);

1 个答案:

答案 0 :(得分:1)

您可能需要检查Base64类。我使用Kiichi Takeuchi编写的Base64类,它给我的结果与我用C#编写的例程验证相同,所以我认为它是正确的。

我必须对您的代码进行一次小的更改才能验证,因为Base64库只编码NSData结构。这是它的样子:

CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *nsd = [[NSData alloc] initWithBytes: cHMAC length:CC_SHA256_DIGEST_LENGTH];

NSString *hash = [Base64 encode:nsd];
[nsd release];
NSLog(@" hash : %@ \r\n", hash);