ioscommoncrypto

How to use CCHmac in iOS?


I want to generate SHA512 with salt in iOS. I found following snippet to achieve this but I found that CCHmac() function is for mac.

-(NSString *)hashString:(NSString *)data withSalt:(NSString *)salt
{
    const char *cKey  = [salt cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    
    NSString *hash;
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
    
    for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", cHMAC[i]];
    }

    hash = output;
    return hash;
}

If I use CC_SHA512() function, then how will I use the salt string?


Solution

  • Example of SHA256 HMAC:

    + (NSData *)doHmac:(NSData *)dataIn key:(NSData *)salt
    {
        NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
        CCHmac( kCCHmacAlgSHA256,
                salt.bytes, salt.length,
                dataIn.bytes, dataIn.length,
                macOut.mutableBytes);
    
        return macOut;
    }