Progressive HMAC SHA256 in Objective-C

倖福魔咒の 提交于 2019-12-13 18:23:25

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/31000886/progressive-hmac-sha256-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!