SPB Git

Repository Public

Hashing.swift 1.8 KB 39 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Security/Hashing.swift3// Description: SHA-256 of data and of files read as a stream (never a whole file in memory), plus base64url coding.4import CryptoKit5import Foundation67public enum Hashing {8    public static func sha256Hex(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }9    public static func hex(_ digest: SHA256.Digest) -> String { digest.map { String(format: "%02x", $0) }.joined() }10    /// SHA-256 of a file (or of its first `length` bytes), read in 1 MiB blocks. Cancellable.11    public static func sha256Hex(of url: URL, length: Int64? = nil, into hasher: inout SHA256) throws -> Int64 {12        let h = try FileHandle(forReadingFrom: url)13        defer { try? h.close() }14        var total: Int64 = 015        while true {16            try Task.checkCancellation()17            var want = 1 << 2018            if let length { want = Int(min(Int64(want), length - total)); if want <= 0 { break } }19            guard let block = try h.read(upToCount: want), !block.isEmpty else { break }20            hasher.update(data: block); total += Int64(block.count)21        }22        return total23    }24    public static func sha256Hex(of url: URL) throws -> (sha256: String, size: Int64) {25        var hasher = SHA256()26        let n = try sha256Hex(of: url, into: &hasher)27        return (hex(hasher.finalize()), n)28    }29}3031extension Data {32    public init?(base64URL s: String) {33        var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")34        while t.count % 4 != 0 { t.append("=") }35        self.init(base64Encoded: t)36    }37    public var base64URL: String { base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") }38}39
Files main
Menu

Theme