开发者

php to iphone code - CCHmac kCCHmacAlgSHA256

开发者 https://www.devze.com 2023-02-27 02:44 出处:网络
I am trying to login to my server using hmac sha256 encryption, i have working code in php, but can\'t get it working in iphone and traced it to that the hmac in iphone is yielding different output to

I am trying to login to my server using hmac sha256 encryption, i have working code in php, but can't get it working in iphone and traced it to that the hmac in iphone is yielding different output to php code, given same inputs php code is

  $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 code is

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_LE开发者_运维百科NGTH];

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

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


You may want to check your Base64 class. I use the Base64 class written by Kiichi Takeuchi and it gives me identical results to a routine I wrote in C# to verify, so I assume it's correct.

I had to make one small change to your code to verify, as the Base64 library only encodes an NSData structure. Here's what it looks like:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消