xcode ios HMAC SHA 256 hashing

gdubs picture gdubs · Jan 25, 2013 · Viewed 18.2k times · Source

So I'm trying to figure out how to do a hmacshad256 hash on ios as that's the hash I did for the wcf service api I made. I've been trying to look for some info about it but would usually just end up getting a SHA-256 hash.

This is the only reference I have:

Need to generate HMAC SHA256 hash in Objective C as in Java

And I'm not sure if that's the only way to do it (importing a java hmac class)

Any help is appreciated.

Thanks!

Answer

Juraj Antas picture Juraj Antas · Jun 27, 2013
NSString * parameters = @"string to hash"
NSString *salt = @"saltStringHere";
NSData *saltData = [salt dataUsingEncoding:NSUTF8StringEncoding];
NSData *paramData = [parameters dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData* hash = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH ];
CCHmac(kCCHmacAlgSHA256, saltData.bytes, saltData.length, paramData.bytes, paramData.length, hash.mutableBytes);
NSString *base64Hash = [hash base64Encoding];

and also

#import <CommonCrypto/CommonHMAC.h>

Since base64Encoding is deprecated from iOS 7.0, the last line should be:

NSString *base64Hash = [hash base64EncodedStringWithOptions:0];