Skip to content

Instantly share code, notes, and snippets.

@whutao
Last active May 26, 2024 16:48
Show Gist options
  • Select an option

  • Save whutao/e74c0067cf104f7b975e177f8392adc5 to your computer and use it in GitHub Desktop.

Select an option

Save whutao/e74c0067cf104f7b975e177f8392adc5 to your computer and use it in GitHub Desktop.
Calculating MD5 hash of a file in Swift
import CryptoKit
import Foundation
func md5File(from url: URL, bufferSize: Int = 1024 * 1024) throws -> Data {
let file = try FileHandle(forReadingFrom: url)
defer {
file.closeFile()
}
var md5 = CryptoKit.Insecure.MD5()
while autoreleasepool(invoking: {
let data = file.readData(ofLength: bufferSize)
if data.isNotEmpty {
md5.update(data: data)
return true
} else {
return false
}
}) {
}
return Data(md5.finalize())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment