iPhone and HMAC-SHA-1 encoding

nownot picture nownot · Apr 9, 2009 · Viewed 14.6k times · Source

im trying to get a call to amazon web service and im stuck on getting the signature, looked at this but i still have a question on it.

using this example what is the

NSData *keyData;
NSData *clearTextData

? what do i need to pass for these two values?

/*
  inputs:
  NSData *keyData;
  NSData *clearTextData
*/

uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};

CCHmacContext hmacContext;
CCHmacInit(&hmacContext, kCCHmacAlgSHA1, keyData.bytes, keyData.length);
CCHmacUpdate(&hmacContext, clearTextData.bytes, clearTextData.length);
CCHmacFinal(&hmacContext, digest);

NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH]

Answer

KeithF picture KeithF · Jul 5, 2009

I just spent like 4 hours Googling and looking for ways to calculate an unkeyed SHA1 on the iPhone that would match the results of the sha1() function in php. Here was the result:

    #import <CommonCrypto/CommonDigest.h>

    NSString *hashkey = <your data here>;
// PHP uses ASCII encoding, not UTF
const char *s = [hashkey cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];

// This is the destination
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
// This one function does an unkeyed SHA1 hash of your hash data
CC_SHA1(keyData.bytes, keyData.length, digest);

// Now convert to NSData structure to make it usable again
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
// description converts to hex but puts <> around it and spaces every 4 bytes
NSString *hash = [out description];
hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
// hash is now a string with just the 40char hash value in it

Hopefully this will help others who are struggling with SHA1 on the iPhone