I need to implement HMAC MD5 in my iPhone application. The PHP version of the algorithm (implemented by the server side for verification) is here, and I can not change it (this is the API)
function hmac($key, $data) {
$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack("H*",md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;
$message = $k_opad . pack("H*",md5($k_ipad . $data));
return base64_encode(md5($message));
}
I found a couple of objective-C implementations:
- (NSString *)HMACMD5WithKey:(NSString *)key andData:(NSString *)data
{
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_MD5_DIGEST_LENGTH];
CCHmac(kCCHmacAlgMD5, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
NSString *hash = [Base64 encode:HMAC];
return hash;
}
Did not return the same results (PHP! = ObjC).
I played with ObjC implementations, changing the digest length to 32 (the result then has the same length as the PHP implementation), the key length to 64 (corresponding to the first str_pad), but the results are always different.
Can someone tell me how to get the same result in objective-C ??
Edit: since 2 implementations in ObjC return the same result, only one is useful here.