0

I am trying to copy some php to Objective-C and have stumbled upon a slight problem.

The php uses the line substr(hash_hmac('sha256', $string, $token), 0, 20) which outputs

ac56093452148b1f18e4

In Objective-C I use CCHmac like this:

NSData *hmacForKeyAndData(NSString *token, NSString *string)
{
    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
}

which returns NSData which when logged is:

<ac560934 52148b1f 18e4385b cfa4f8cd cebe12c3 99d3281d 9f48c312 d6802449>

which looks the exact same as what php returns from hash_hmac('sha256', $string, $token)

I think you can see my problem here. I have the right output (It just needs trimming to 20 characters), but as NSData. If I convert the NSData to an NSString then I get a load of funny characters. I need to take the NSData <ac560934> and convert it into the string ac560934 Is this even possible? Or should I be using a different approach for the hash_mac?

Thanks

Darren
  • 10,182
  • 20
  • 95
  • 162
  • Take a look at: http://stackoverflow.com/questions/7520615/how-to-convert-an-nsdata-into-an-nsstring-hex-string – kviksilver Feb 26 '15 at 17:03
  • Thank you, that worked. I couldn't find that as there are so many NSData to NSString conversion questions. – Darren Feb 26 '15 at 17:24

0 Answers0