1、在文件超过1G的时候,不能一次性放入内存之中,但是我们还是需要将这个文件进行md5加密,或者hmac系列的加密
这个时候我们需要用到一个系统的api——update系列的方法
注意:参数path为大文件所在的路径。
//MARK:大文件的MD5加密 +(NSString*)fileMD5:(NSString*)path { NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path]; if( handle== nil ) return @"ERROR GETTING FILE MD5"; // file didnt exist CC_MD5_CTX md5; CC_MD5_Init(&md5); BOOL done = NO; while(!done) { NSData* fileData = [handle readDataOfLength:256]; // CHUNK_SIZE CC_MD5_Update(&md5, [fileData bytes], [fileData length]); if( [fileData length] == 0 ) done = YES; } 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; }
//MARK:大文件的hmacSHA256加密 + (NSString *)hmac:(NSString *)path withKey:(NSString *)key { NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path]; if( handle== nil ) return @"ERROR GETTING FILE hmac"; // file didnt exist CCHmacContext ctx; const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; CCHmacInit(&ctx, kCCHmacAlgSHA256, cKey, strlen(cKey)); BOOL done = NO; while(!done) { NSData* fileData = [handle readDataOfLength:256]; CCHmacUpdate(&ctx, [fileData bytes], [fileData length]); if( [fileData length] == 0 ) done = YES; } CCHmacFinal(&ctx, cHMAC); NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)]; const unsigned char *buffer = (const unsigned char *)[HMACData bytes]; NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2]; for (int i = 0; i < HMACData.length; ++i){ [HMAC appendFormat:@"%02x", buffer[i]]; } return HMAC; }
原文地址:https://www.cnblogs.com/yyyyyyyyqs/p/11451618.html
时间: 2024-10-12 02:56:47