I want to encpryt a string with a key using HmacSHA256. The code that everyone uses is below, but there is one thing that does not make sense. Why will we use base64 at the end if all we need is an HmacSHA256 hash?
I tried to see the hash generated after calling the CCHmac method with
NSString *str = [[NSString alloc] initWithData:HMAC encoding:NSASCIIStringEncoding]; NSLog(@"%@", str);
But I do not get the hash generated, I get null or garbage, for example:
2011-10-11 09: 38: 05.082 Hash_HmacSHA256 [368: 207] (null) 2011-10-11 09: 38: 05.085 Hash_HmacSHA256 [368: 207] Rwªb7iså {yyþ§ '(& o ÷ ÛËÚ ¥ M`f
import < CommonCrypto/CommonHMAC.h> NSString *key; NSString *data; const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding]; unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; NSString *hash = [HMAC base64Encoding];
source share