文件MD5

代码如下:

+(NSString*)getFileMD5WithPath:(NSString*)path

{

return(__bridge_transferNSString*)FileMD5HashCreateWithPath((__bridgeCFStringRef)path,FileHashDefaultChunkSizeForReadingData);

}

CFStringRefFileMD5HashCreateWithPath(CFStringReffilePath,size_tchunkSizeForReadingData) {

// Declare needed variables

CFStringRefresult =NULL;

CFReadStreamRefreadStream =NULL;

// Get the file URL

CFURLReffileURL =

CFURLCreateWithFileSystemPath(kCFAllocatorDefault,

(CFStringRef)filePath,

kCFURLPOSIXPathStyle,

(Boolean)false);

if(!fileURL)gotodone;

// Create and open the read stream

readStream =CFReadStreamCreateWithFile(kCFAllocatorDefault,

(CFURLRef)fileURL);

if(!readStream)gotodone;

booldidSucceed = (bool)CFReadStreamOpen(readStream);

if(!didSucceed)gotodone;

// Initialize the hash object

CC_MD5_CTXhashObject;

CC_MD5_Init(&hashObject);

// Make sure chunkSizeForReadingData is valid

if(!chunkSizeForReadingData) {

chunkSizeForReadingData =FileHashDefaultChunkSizeForReadingData;

}

// Feed the data to the hash object

boolhasMoreData =true;

while(hasMoreData) {

uint8_tbuffer[chunkSizeForReadingData];

CFIndexreadBytesCount =CFReadStreamRead(readStream,(UInt8*)buffer,(CFIndex)sizeof(buffer));

if(readBytesCount == -1)break;

if(readBytesCount ==0) {

hasMoreData =false;

continue;

}

CC_MD5_Update(&hashObject,(constvoid*)buffer,(CC_LONG)readBytesCount);

}

// Check if the read operation succeeded

didSucceed = !hasMoreData;

// Compute the hash digest

unsignedchardigest[CC_MD5_DIGEST_LENGTH];

CC_MD5_Final(digest, &hashObject);

// Abort if the read operation failed

if(!didSucceed)gotodone;

// Compute the string result

charhash[2*sizeof(digest) +1];

for(size_ti =0; i

snprintf(hash + (2* i),3,"%02x", (int)(digest[i]));

}

result =CFStringCreateWithCString(kCFAllocatorDefault,(constchar*)hash,kCFStringEncodingUTF8);

done:

if(readStream) {

CFReadStreamClose(readStream);

CFRelease(readStream);

}

if(fileURL) {

CFRelease(fileURL);

}

returnresult;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容