Get MD_5 Hash File on iPhone

In my project, I need to get the hash code of the MD_5 file in iphone. uptill now i 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 this row of byte array of images

  UIImage *image = [UIImage imageNamed:@"sf_small.png"]; NSData *data = UIImagePNGRepresentation(image); NSString *str = [NSString stringWithFormat:@"%@",data]; NSString *temp = [self getMD5FromString:str]; 

now i get the hash code successfully. But when on the webpage I get the md_5 hash of the same file, then it gives me a great hash code. in the web part i'm using php code

  md5_file(string $filename); 

this php code gives me a differnet hash code and the iphone code gives me different hash codes for the same image. Please tell me what could be the problem.

Thanks a lot!

tic.png

+4
source share
2 answers

There are two reasons. The first is because raw bytes -> string -> UTF-8 process damaged some non-ASCII characters. Note that you can directly get a pointer to bytes from NSData :

 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 reason is related to the PNG process → raw image → PNG. There is no guarantee that the same image will be compressed to the same PNG image in different libraries, and, of course, you will have a different MD5. You can simply not read the file as an image as a whole, since it can 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); ... 
+7
source

Instead of out UTF8String use NSMacOSRomanStringEncoding , it accepts 8-bit characters.

Better, use an NSData pointer without conversion, see: @KennyTM.

+1
source

All Articles