1

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?

NSPratik
  • 4,714
  • 7
  • 51
  • 81
  • 2
    Hashes and HMACs aren't the same thing? If you wanted a salted hash of the string you want to use something like `CCKeyDerivationPBKDF`. See [this](http://security.stackexchange.com/questions/29951/salted-hashes-vs-hmac) for more info. – Rich Jan 05 '15 at 14:45
  • 2
    Also `CCHmac` is not OS X only (the mac in the name is nothing to do with it being Mac (OS X) only), [this question](http://stackoverflow.com/questions/26655999/create-hash-in-swift-using-key-and-message) uses it. – Rich Jan 05 '15 at 14:58
  • 1
    Bet not to name a string argument `data`. – zaph Jan 06 '15 at 23:57

2 Answers2

6

I was missing following line:

#import <CommonCrypto/CommonHMAC.h>

Actually, < CommonCrypto / CommonCryptor.h > was already added in my code. So, at first look, I thought that there is no worry about importing particular header file. But, suddenly I realize that I will have to import another header file.

NSPratik
  • 4,714
  • 7
  • 51
  • 81
4

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;
}
zaph
  • 111,848
  • 21
  • 189
  • 228