So, you want to do MD5 hashing on the iPhone?
This works with the standard libraries that come with Mac OS X:
#include <openssl/md5.h>
NSString *someString = @”I like Doritos.”;
NSData *data = [someString dataUsingEncoding:PickYourEncoding];
unsigned char *digest = MD5([data bytes], [data length], NULL);
Yeah, it works. If you need to be absolutely thread safe, use your own buffer instead of using the static one. Now, how do we make a cool helper class out of this? On the iPhone, well, we don’t. It took me a while to figure out that the cool kids use CC_MD5:
NSString *someString = @”I like Doritos.”;
const char *str = [someString UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);
A MD5 digest is a 16 byte binary result, not a string. So CC_MD5_DIGEST_LENGTH is defined as 16 in CommonDigest.h.
Let’s go through the result and append the %02x format, so we get a proper hash.
I ended up doing it this way:
+ (NSString *)md5HexDigestStringOfString:(NSString *)inString {
const char *str = [inString UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);
NSMutableString *returnString = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[returnString appendFormat:@”%02x”,result[i]];
}
return returnString;
}
For CC_MD5 you need to import <CommonCrypto/CommonDigest.h> which is part of the security framework on the iPhone.
Happy coding!