How to calculate the MD5 in objective C ?
md5 is available on the iPhone and can be added as an extension for ie NSString
and NSData
like below.
MyExtensions.h
@interfaceNSString(MyExtensions)-(NSString*) md5;@end@interfaceNSData(MyExtensions)-(NSString*)md5;@end
MyExtensions.m
#import "MyExtensions.h"#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access@implementationNSString(MyExtensions)-(NSString*) md5
{constchar*cStr =[self UTF8String];unsignedchar result[16];
CC_MD5( cStr, strlen(cStr), result );// This is the md5 callreturn[NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]];}@end@implementationNSData(MyExtensions)-(NSString*)md5
{unsignedchar result[16];
CC_MD5( self.bytes, self.length, result );// This is the md5 callreturn[NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]];}@end
EDIT
Added NSData md5 because I needed it myself and thought this is a good place to save this little snippet...