Does anyone know a way to calculate de SHA-256 hash of a file without having to load the entire file on memory?
I would be ideal to use apple's CryptoKit library
Does anyone know a way to calculate de SHA-256 hash of a file without having to load the entire file on memory?
I would be ideal to use apple's CryptoKit library
You could use a FileHandle
to read the data in chunks, and pass these into the hasher:
import CryptoKit
func getSHA256(forFile url: URL) throws -> SHA256.Digest {
let handle = try FileHandle(forReadingFrom: url)
var hasher = SHA256()
while autoreleasepool(invoking: {
let nextChunk = handle.readData(ofLength: SHA256.blockByteCount)
guard !nextChunk.isEmpty else { return false }
hasher.update(data: nextChunk)
return true
}) { }
let digest = hasher.finalize()
return digest
// Here's how to convert to string form
//return digest.map { String(format: "%02hhx", $0) }.joined()
}
Create a hasher:
With each chunk you read (in whatever way or size you want to read it), update the hasher:
(or if you have an
UnsafeRawBufferPointer
, you can pass that)And when you're done, finalize it: