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
Create a hasher:
let hasher = SHA256()
With each chunk you read (in whatever way or size you want to read it), update the hasher:
hasher.update(data: blockOfData)
(or if you have an UnsafeRawBufferPointer
, you can pass that)
And when you're done, finalize it:
let hash = haser.finalize()
FileHandle
and InputStream
but my memory usage goes up a lot (800 mb). –
Capitalism autoreleasepool{}
block so it'll let go of temporary memory you allocate in the loop. –
Jollification 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()
}
© 2022 - 2024 — McMap. All rights reserved.