In my project i need to get the MD_5 hash code of the file in iphone. uptill now i have found the following code to get md_5 of any image/any file.
-(NSString *)getMD5FromString:(NSString *)source{
const char *src = [source UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(src, strlen(src), result);
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]
]lowercaseString];
}
using this code to get the ByteContent of the image and then get the md_5 of that image byte array string
UIImage *image = [UIImage imageNamed:@"sf_small.png"];
NSData *data = UIImagePNGRepresentation(image);
NSString *str = [NSString stringWithFormat:@"%@",data];
NSString *temp = [self getMD5FromString:str];
now i am getting a hash code succesfully But when on the web side i get the md_5 hash code of same file then it gives me diferent hash code. in Web side i am using PHP code
md5_file(string $filename);
this PHP code gives me differnet hash code and iphone code gives me different hash code for same image. Please tell me what can be the problem..
Thanks alot!
tic.png
There are 2 causes. The first is because the raw bytes → string → UTF-8 process corrupted some non-ASCII characters. Note that you can get a pointer to the bytes from an NSData directly:
UIImage* image = [UIImage imageNamed:@"sf_small.png"];
NSData* data = UIImagePNGRepresentation(image);
const void* src = [data bytes];
NSUInteger len = [data length];
CC_MD5(src, len, result);
...
The second cause is because of the PNG → raw image → PNG process. There is no guarentee that the same image will compress to the same PNG representation in different libraries, and of course you'll have different MD5. You could just avoid reading the file as image altogether, as it's possible read the file directly as data:
NSData* data = [NSData dataWithContentsOfFile:@"sf_small.png"];
const void* src = [data bytes];
NSUInteger len = [data length];
CC_MD5(src, len, result);
...
Instead of outing UTF8String
use NSMacOSRomanStringEncoding
, it accepts 8 bit chars.
Better, use the NSData pointer without conversion, see: @KennyTM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With