Last active
May 26, 2024 16:48
-
-
Save whutao/e74c0067cf104f7b975e177f8392adc5 to your computer and use it in GitHub Desktop.
Calculating MD5 hash of a file in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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