Repository Public
1// SP Drive iOS2// File: Sync/IntegrityVerifier.swift3// Description: SHA-256 of files and of slices of files, streamed from disk (a large file is never loaded in memory).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import CryptoKit8import Foundation910public enum IntegrityVerifier {11 static let bufferSize = 1 << 201213 public static func hex(_ digest: SHA256.Digest) -> String { digest.map { String(format: "%02x", $0) }.joined() }14 public static func sha256(_ data: Data) -> String { hex(SHA256.hash(data: data)) }1516 /// SHA-256 of a whole file.17 public static func sha256(of url: URL) throws -> String {18 let h = try FileHandle(forReadingFrom: url)19 defer { try? h.close() }20 var hasher = SHA256()21 while true {22 try Task.checkCancellation()23 guard let chunk = try h.read(upToCount: bufferSize), !chunk.isEmpty else { break }24 hasher.update(data: chunk)25 }26 return hex(hasher.finalize())27 }2829 /// True when the file's content has exactly this hash (case-insensitive hex).30 public static func verify(_ url: URL, sha256 expected: String) -> Bool {31 guard let actual = try? sha256(of: url) else { return false }32 return actual == expected.lowercased()33 }3435 /// Copies `length` bytes of `source` starting at `offset` into `destination` and returns the SHA-256 of that slice.36 public static func slice(_ source: URL, offset: Int64, length: Int64, to destination: URL) throws -> String {37 let input = try FileHandle(forReadingFrom: source)38 defer { try? input.close() }39 try input.seek(toOffset: UInt64(offset))40 FileManager.default.createFile(atPath: destination.path, contents: nil)41 let out = try FileHandle(forWritingTo: destination)42 defer { try? out.close() }43 var hasher = SHA256()44 var left = length45 while left > 0 {46 guard let chunk = try input.read(upToCount: Int(min(Int64(bufferSize), left))), !chunk.isEmpty else { break }47 hasher.update(data: chunk)48 try out.write(contentsOf: chunk)49 left -= Int64(chunk.count)50 }51 guard left == 0 else { throw CocoaError(.fileReadCorruptFile) }52 return hex(hasher.finalize())53 }5455 public static func size(of url: URL) -> Int64 {56 ((try? FileManager.default.attributesOfItem(atPath: url.path))?[.size] as? NSNumber)?.int64Value ?? 057 }58}59