2012-02-26 84 views
10

給定的消息和鹽我如何編碼它返回散列的字符串?如何在可可/ iOS的SHA哈希

我需要重現PHP函數:

hash_hmac('sha256','message','salt'); 

感謝

+1

這個問題有一個看起來不錯的答案:http://stackoverflow.com/問題/ 6228092 /我怎麼能計算一個sha-2-idealally-sha-256-or-sha-512-hash-in-ios – Bogatyr 2012-02-26 16:10:31

+1

是的,但不知道如何使用鹽... – Addev 2012-02-26 17:00:47

回答

39

找到了答案:

#import <CommonCrypto/CommonHMAC.h> 

-(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; 

}