一般我们比较文件的完整性,就是对文件进行哈希计算,通常就是MD5或者SHA256或者SHA1计算,如果生成的结果字符串是一样的,则表明文件没有被篡改
比如我们在网络上下载的安装包,下载时都会提示MD5或者SHA1的校验码是多少?有没有想过校验码是如何生成的了?以下就是用Objective-C来对文件计算checksum即校验码是否 服务器端存储的一致,如果是一致的,则表示文件是完整的
#import "FileChecksumUtil.h"
#import <CommonCrypto/CommonDigest.h>
@implementation FileChecksumUtil
// MD5 hash for file 对文件进行MD5 HASH计算
+ (NSString * _Nullable)md5HashForFileWithFullPath:(NSString *)fullPath {
NSFileManager *fileManager = [NSFileManager defaultManager];
// Make sure the file exists
if( [fileManager fileExistsAtPath:fullPath isDirectory:nil]) {
NSData *data = [NSData dataWithContentsOfFile:fullPath];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(data.bytes, (CC_LONG)data.length, digest);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
return nil;
}
// 对文件进行SHA256 HASH计算
+ (NSString * _Nullable)sha256HashForFileWithFullPath:(NSString *)fullPath {
NSFileManager *fileManager = [NSFileManager defaultManager];
// Make sure the file exists
if( [fileManager fileExistsAtPath:fullPath isDirectory:nil] ) {
NSData *data = [NSData dataWithContentsOfFile:fullPath];
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
return nil;
}
@end
// 测试
NSString *fullPath = @"/Users/victorzhang/Documents/20200730-资料.zip";
NSString *md5 = [FileChecksumUtil md5HashForFileWithFullPath:fullPath];
NSString *sha1 = [FileChecksumUtil sha256HashForFileWithFullPath:fullPath];
NSLog(@"MD5: %@", md5);
NSLog(@"SHA256: %@", sha1);
输出
MD5: db620a4c2f33899dfea298fb8377938b
SHA256: f6b77493ce07b40b25c6c2789284d92a7d23e0d68b95df766f1f2144f4fae6ad