Sometimes it is necessary to implement some cryptographic functions for security reasons within your iOS apps. In one of our projects I was faced with the problem of implementing some kind of a two-step registration/confirmation process with a iOS app and a corresponding server-side interface. We decided to implement this by using a generated confirmation code based on HMAC and MD5. Since there is no native support of the iOS framework to realize this, I needed to implement it on my own.
Due to this post Implementing HMAC encryption algorithm in iPhone application it was quite easy to implement a simple category for NSString to provide this functionality. The following code creates a HMAC+MD5 encrypted string based on a given secret and returns it in a hexadecimal string representation.
#include <CommonCrypto/CommonDigest.h> #include <CommonCrypto/CommonHMAC.h> #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> @implementation NSString (HMAC) - (NSString*) HMACWithSecret:(NSString*) secret { CCHmacContext ctx; const char *key = [secret UTF8String]; const char *str = [self UTF8String]; unsigned char mac[CC_MD5_DIGEST_LENGTH]; char hexmac[2 * CC_MD5_DIGEST_LENGTH + 1]; char *p; CCHmacInit( &ctx, kCCHmacAlgMD5, key, strlen( key )); CCHmacUpdate( &ctx, str, strlen(str) ); CCHmacFinal( &ctx, mac ); p = hexmac; for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ) { snprintf( p, 3, "%02x", mac[ i ] ); p += 2; } return [NSString stringWithUTF8String:hexmac]; } @end
You can now simply use this like the following:
NSString *strToEncrypt = @"mytexttoencyrpt"; NSString *secret = @"SECRET"; NSString *hexHmac = [strToEncrypt HMACWithSecret:secret]; NSLog(@"HMAC in hex is %@", hexHmac); //Outputs: HMAC in hex is 3849b37cf06d014a13839a9062b5723d
Find the source code for the NSString category at HMAC category.
Leave a Reply