Search code examples
javascriptobjective-ccryptographyhmaccryptojs

Progressive HMAC SHA256 in Objective-C


I need to generate a hash using HMAC SHA256. I am using the following code in JavaScript. I need an equivalent code in Objective-C.

function serialize( obj ) {
   return Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
}

var query = {
  Action            : 'MyAction',
  SignatureMethod   : 'HmacSHA256',
};

var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, 'MYVALUE');
var queryString = ['POST', 'm.service.it', '/api/v2', serialize(sorted)].join('\n');

hmac.update(queryString);
query.Signature = CryptoJS.enc.Base64.stringify(hmac.finalize());

How implement this in Objective-C?


Solution

  • HMAC-SHA256 sample code:

    + (NSData *)hmacSha256:(NSData *)dataIn
                   key:(NSData *)key
    {
        NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
        CCHmac( kCCHmacAlgSHA256,
               key.bytes,
               key.length,
               dataIn.bytes,
               dataIn.length,
               macOut.mutableBytes);
    
        return macOut;
    }
    

    Notes:

    1. Add Security.framework to the project
    2. Common Crypto must be included:
      #import <CommonCrypto/CommonCrypto.h>

    3. This is data in and out, add any conversions to desired representations before and after.
      Conversions could be string to data on input and data to Base64 on output:
      NSData *data = [@"string" dataUsingEncoding:NSUTF8StringEncoding];
      NSString *string = [data base64EncodedStringWithOptions:0];