Sha256 hash for large files / data on iOS in fast

Below is a general solution for getting a data hash in Swift ( How can I hash a file on iOS using fast 3? ). However, this solution does not work for big data, since it must simultaneously load all the data into memory, which can lead to performance problems or even crashes on the iOS device. There is also a solution for a large file, but it is not in Swift: a hash for big data .

func sha256(data: Data) -> Data {
    var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes {digestBytes in
        data.withUnsafeBytes {messageBytes in
            CC_SHA256(messageBytes, CC_LONG(data.count), digestBytes)
        }
    }
    return digestData
}

let testData: Data = "testString".data(using: .utf8)!
print("testData: \(testData.map { String(format: "%02hhx", $0) }.joined())")
let testHash = sha256(data:testData)
print("testHash: \(testHash.map { String(format: "%02hhx", $0) }.joined())")

How can I write a function to get the sha256 hash for big data or how to edit the code snippet above?

0
source share

Source: https://habr.com/ru/post/1672855/


All Articles