1

I'm currently developing an app which needs to send authentication data with it to a provided API. Basically it needs to generate a SHA256 based on the DATA you want to send, based on a SHARED KEY.

The API is usually used with PHP, which provides something like this handy function:

$key = hash_hmac('sha256', $postdata , $sharedkey);

in IOS function:

CC_SHA256(const void *postdata, CC_LONG len, unsigned char *md)

but this function is not an argument for key.

whether there are ways to do it?

Denis
  • 11
  • 2
  • In Swift I would use this: https://github.com/krzyzanowskim/CryptoSwift – Luca Angioloni Dec 18 '16 at 15:05
  • Possible duplicate of: http://stackoverflow.com/questions/14516191/xcode-ios-hmac-sha-256-hashing – Luca Angioloni Dec 18 '16 at 15:06
  • @LucaAngioloni It is best to avoid using CryptoSwift, amoung other things it is 100 to 1000 times slower than Common Crypto based implementations. Apple's Common Crypto is FIPS certified and as such has been well vetted, using CryptoSwift is taking a chance on correctness and security. – zaph Dec 19 '16 at 17:47

1 Answers1

0
+ (NSString *)hashedString:(NSString *)value withKey:(NSString *)key
{
   const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
   const char *cData = [value cStringUsingEncoding:NSUTF8StringEncoding];

   unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

   CCHmac (kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

   NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];

   for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
       [output appendFormat:@"%02x", cHMAC[i]];
   }

   return output;
}

do not forget to import the source code #import <CommonCrypto/CommonHMAC.h>

this method does what I meant. My problem is solved.

Denis
  • 11
  • 2