Question

I create an MD5 of a file that is deployed with my bundle to decide if I need to import it. My problem is that when I create the MD5 is always different. Even when I call the MD5 method 10 times in a loop with the same data, I got different results.

Here is my MD% method:

- (NSString*)hashForData:(NSData*)data
{
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5((__bridge const void*)(data), (CC_LONG)data.length, md5Buffer);
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", md5Buffer[i]];

    return output;
}

- (NSData*)data
{
    if (!_data) {
        _data = [NSData dataWithContentsOfFile:_path];
    }
    return _data;
}

Any idea what could be wrong?

Was it helpful?

Solution

Shouldn't that be:

CC_MD5((__bridge const void*)([data bytes]), (CC_LONG)[data length], md5Buffer);
//                            ^^^^^^^^^^^^            ^^^^^^^^^^^^^

(i.e. you are calculating the MD5 hash of the NSData object (and adjacent memory) instead of the data within the NSData object).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top