-1

我正在尝试使用 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>";

目标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);
4

1 回答 1

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);
于 2011-05-02T18:58:33.030 回答