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?

4

2 回答 2

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.

于 2015-01-06T12:17:42.037 回答
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;
}
于 2015-01-05T23:34:15.107 回答