首先需要引入用的的Cocoa类CommonCrypto,由于CommonCrypto没有兼容 Swift,需要将以下导入到项目的Bridging-Header.h
文件中:
#import <CommonCrypto/CommonCrypto.h>
由于移动设备的内存有限,以下代码实现是将文件分块读出并且计算md5值的方法,兼容Swift 3.0:
func fileMD5(_ path: String) -> String? {
let handle = FileHandle(forReadingAtPath: path)
if handle == nil {
return nil
}
let ctx = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: MemoryLayout<CC_MD5_CTX>.size)
CC_MD5_Init(ctx)
var done = false
while !done {
let fileData = handle?.readData(ofLength: 256)
fileData?.withUnsafeBytes {(bytes: UnsafePointer<CChar>)->Void in
//Use `bytes` inside this closure
//...
CC_MD5_Update(ctx, bytes, CC_LONG(fileData!.count))
}
if fileData?.count == 0 {
done = true
}
}
//unsigned char digest[CC_MD5_DIGEST_LENGTH];
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let digest = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5_Final(digest, ctx);
var hash = ""
for i in 0..<digestLen {
hash += String(format: "%02x", (digest[i]))
}
digest.deinitialize()
ctx.deinitialize()
return hash;
}