您可以分块计算MD5校验和,例如在?中有没有一个MD5库不需要同时输入全部内容?。
这是使用Swift的可能实现(现已针对Swift 5更新)
import CommonCryptofunc md5File(url: URL) -> Data? { let bufferSize = 1024 * 1024 do { // Open file for reading: let file = try FileHandle(forReadingFrom: url) defer { file.closeFile() } // Create and initialize MD5 context: var context = CC_MD5_CTX() CC_MD5_Init(&context) // Read up to `bufferSize` bytes, until EOF is reached, and update MD5 context: while autoreleasepool(invoking: { let data = file.readData(ofLength: bufferSize) if data.count > 0 { data.withUnsafeBytes { _ = CC_MD5_Update(&context,file.readData().baseAddress, numericCast(data.count)) } return true // Continue } else { return false // End of file } }) { } // Compute the MD5 digest: var digest: [UInt8] = Array(repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) _ = CC_MD5_Final(&digest, &context) return Data(digest) } catch { print("Cannot open file:", error.localizedDescription) return nil }}
需要自动释放池来释放所返回的内存
Beckert注意到这一点并提供了实现。,否则,整个文件(可能很大)将被加载到内存中。感谢Abhi
String?
如果您需要摘要作为十六进制编码的字符串,则将返回类型更改为
return digest并替换
let hexDigest = digest.map { String(format: "%02hhx", ) }.joined()return hexDigest
通过
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)