1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| CG_INLINE NSString* MD5FromString(NSString *sourceString) { const char *original_str = [sourceString UTF8String]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(original_str, strlen(original_str), result); NSMutableString *hash = [NSMutableString string]; for (int i = 0; i < 16; i++) [hash appendFormat:@"%02X", result[i]]; return [hash lowercaseString]; }
CG_INLINE NSString *MD5ForFile(NSString *path) { NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path]; if( handle== nil ) { return nil; } CC_MD5_CTX md5; CC_MD5_Init(&md5); BOOL done = NO; while(!done) { @autoreleasepool { NSData* fileData = [handle readDataOfLength:256]; CC_MD5_Update(&md5, [fileData bytes], [fileData length]); if( [fileData length] == 0 ) done = YES; fileData = nil; } } unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5_Final(digest, &md5); NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]]; return s; }
|