文件在下载完成之后通常会进行Hash校验,因此客户端通过计算文件Hash值验证机制来确保文件上传下载后的完整性.计算方式比较常用的有MD5和SHA,两种计算方式不可逆和无冲突,其中MD5计算文件的Hash值较为普遍.
SHA加密
导入头文件
#include <CommonCrypto/CommonDigest.h>
+ (NSString *)computeHashForFile:(NSURL *)fileURL {
NSString *fileContentsHash;
if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
NSData *fileContents = [NSData dataWithContentsOfURL:fileURL];
fileContentsHash = [self computeHashForData:fileContents];
}
return fileContentsHash;
}
+ (NSString *)computeHashForData:(NSData *)inputData {
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(inputData.bytes, (CC_LONG)inputData.length, digest);
NSMutableString* inputHash = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[inputHash appendFormat:@"%02x", digest[i]];
}
return inputHash;
}
MD5计算
+ (NSString *)computeHashForFile:(NSURL *)fileURL {
NSString *fileContentsHash;
if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
NSData *fileContents = [NSData dataWithContentsOfURL:fileURL];
fileContentsHash = [self computeHashForData:fileContents];
}
return fileContentsHash;
}
+ (NSString *)computeHashForData:(NSData *)inputData {
uint8_t digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(inputData.bytes, (CC_LONG)inputData.length, digest);
NSMutableString *inputHash = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[inputHash appendFormat:@"%02x", digest[i]];
}
return inputHash;
}
字符串Hash值计算:
+ (NSString *)computeHashForString:(NSString *)string {
const char *cStr = [string UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
NSMutableString *hash = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x", digest[i]];
}
return hash;
}