views:

1674

answers:

5

How to calculate the MD5 in objective C ?

+1  A: 

This has been asked before here on stackoverflow:

Miha Hribar
A: 

My guess is that you can fairly easily port a C routine that calculates MD5. And they're easy to find.

Artelius
A: 

If you know how to do a HTTP GET you can do it with this API http://www.filemd5.net/API

JohnnieWalker
You probably don't want to use that. Why would you transfer your data across the internet to a third party to analyze, when you can do it locally?
+10  A: 

md5 is available on the iPhone and can be added as an extension for ie NSString and NSData like below.

MyExtensions.h

@interface NSString (MyExtensions)
- (NSString *) md5;
@end

@interface NSData (MyExtensions)
- (NSString*)md5;
@end

MyExtensions.m

#import "MyExtensions.h"
#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access

@implementation NSString (MyExtensions)
- (NSString *) md5
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result ); // This is the md5 call
    return [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

@implementation NSData (MyExtensions)
- (NSString*)md5
{
    unsigned char result[16];
    CC_MD5( self.bytes, self.length, result ); // This is the md5 call
    return [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...

epatel
Great little snippet - thanks (+1).
jkp
A: 

If anyone was looking for a solution to this for a REST API implementation, like I was for hours. You can check out my blog for the solution. I was able to produce a correctly formatted utf-8 MD5 hash all in lower case using a class method that I produced.

see it here

http://www.saobart.com/md5-has-in-objective-c/

Chris Beaven