2

I'm current having some trouble with this code Snippet:

- (NSString *) md5:( NSString *) str 
{
    const char *cStr = [str 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]
            ];  
}

This method is generating a hash of a downloaded XML File, which is complete different from the PHP function md5().

So how do I get the Hash which is identically to PHPs one or vice versa.

Bene
  • 636
  • 1
  • 8
  • 24
  • 2
    To get the identical hash, supply the identical source data. Log the exact bytes of the *input*, not the output, for both Objective-C and PHP. Start with a small file to test with. – Greg Hewgill May 11 '12 at 09:02
  • There is another MD5 implementation here: http://stackoverflow.com/a/3104362/187954 – Michael Robinson May 11 '12 at 09:01

2 Answers2

2

If You do echo md5('hello') in PHP You would receive a 32 char long string, but when You use Your code snippet in ObjC, You transform the string chars to the HEX format (by using the formater %02x) - see here https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265 and here: Unsigned Char Array to Hex Representation NSString.

And You use only half the MD5 string chars to create this HEX formated string... Either return the result immediately or do the same HEX transformation in PHP :-)

Community
  • 1
  • 1
shadyyx
  • 15,825
  • 6
  • 60
  • 95
0

The function found in this answer does the job perfectly in my testing:

#import <CommonCrypto/CommonDigest.h>

...
+ (NSString*)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);

    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}
...

Matched up with PHP's implementation exactly. It originally comes from the Facebook Connect source code.

Community
  • 1
  • 1
Wes Cossick
  • 2,923
  • 2
  • 20
  • 35