SHA-256 of large file using CryptoKit

1.5k views Asked by At

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

2

There are 2 answers

5
Rob Napier On BEST ANSWER

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()
0
Apptek Studios On

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()
}