It's worth mentioning that the OpenSSL methods are deprecated on more recent versions of OS X, and the MD5 digest is conventionally lower case. Personally I'm more a fan of the unrolled style for efficiency, and I think using ObjC categories for this is a better fit.
For MD5Digest.h:
#include
@interface NSString (MD5Digest)
- (NSString*) md5Digest;
@end
@interface NSData (MD5Digest)
- (NSString*) md5Digest;
@end
And MD5Digest.m:
#include <CommonCrypto/CommonDigest.h>
#include "MD5Digest.h"
static NSString* md5Digest(const void *data, CC_LONG length)
{
unsigned char digest[CC_MD5_DIGEST_LENGTH];
unsigned char* d = CC_MD5(data, length, digest);
return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10], d[11], d[12], d[13], d[14], d[15],
nil];
}
@implementation NSString (MD5Digest)
- (NSString*) md5Digest
{
return md5Digest([self UTF8String], [self lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
}
@end
@implementation NSData (MD5Digest)
- (NSString*) md5Digest
{
return md5Digest([self bytes], [self length]);
}
@end