10

Given the message and the salt how can I encode it returning the hashed string?

I need reproduce the php function:

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

Thanks

Addev
  • 31,819
  • 51
  • 183
  • 302
  • 1
    This question has an answer that looks good: http://stackoverflow.com/questions/6228092/how-can-i-compute-a-sha-2-ideally-sha-256-or-sha-512-hash-in-ios – Bogatyr Feb 26 '12 at 16:10
  • 1
    Yep but don't know how to use the salt... – Addev Feb 26 '12 at 17:00

1 Answers1

39

Found the answer:

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

}
IluTov
  • 6,807
  • 6
  • 41
  • 103
Addev
  • 31,819
  • 51
  • 183
  • 302