iPhone开发中 验证”字符串“/“文件”的MD5的加密
+(NSString*) md5:(NSString*) str { const char *cStr = [str UTF8String]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5( cStr, strlen(cStr), result ); NSMutableString *hash = [NSMutableString string]; for(int i=0;i<CC_MD5_DIGEST_LENGTH;i++) { [hash appendFormat:@"%02X",result[i]]; } return [hash lowercaseString]; } #define CHUNK_SIZE 1024 +(NSString *)file_md5:(NSString*) path { NSFileHandle* handle = [NSFileHandle fileHandleForReadingAtPath:path]; if(handle == nil) return nil; CC_MD5_CTX md5_ctx; CC_MD5_Init(&md5_ctx); NSData* filedata; do { filedata = [handle readDataOfLength:CHUNK_SIZE]; CC_MD5_Update(&md5_ctx, [filedata bytes], [filedata length]); } while([filedata length]); unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5_Final(result, &md5_ctx); [handle closeFile]; NSMutableString *hash = [NSMutableString string]; for(int i=0;i<CC_MD5_DIGEST_LENGTH;i++) { [hash appendFormat:@"%02x",result[i]]; } return [hash lowercaseString]; } +(NSString *)NSStringToMD5String:(NSString *)str{ NSString *result = nil; if(str) { unsigned char digest[16]; const char *cStr=[str UTF8String]; CC_MD5(cStr, strlen(cStr), digest); result = [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]]; result = [result uppercaseString]; } return result; }