0

I'm downloading file (~ 300MB) using Alamofire. After download and save, I have to calculate and compare SHA1 from this file, so I do this:

let data = Data(contentsOf: url)
let sha1 = data.sha1

That generate a problem. All bytes are coped to ram memory. How can I avoid this?

function to calculate:

extension Data {
    func sha1() -> String {
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        self.withUnsafeBytes {
            _ = CC_SHA1($0, CC_LONG(self.count), &digest)
        }
        let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joined()
    }
}
kerstin
  • 21
  • 2
  • 1
    Have a look at [Swift Calculate MD5 Checksum for Large Files](http://stackoverflow.com/questions/42935148/swift-calculate-md5-checksum-for-large-files). The same approach works with SHA1 and other digests. – Martin R May 08 '17 at 14:14
  • Information about how to map files into virtual memory can be found in Apple's Documentation https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemAdvancedPT/MappingFilesIntoMemory/MappingFilesIntoMemory.html – Scott Thompson May 08 '17 at 14:15
  • I've marked this as a dupe as I don't see the value of listing the same solution for each and every hash (there are 6 additional SHA-2 hashes and 4 additional SHA-3 hashes) – Maarten Bodewes May 08 '17 at 18:28
  • Note that neither MD5 nor SHA-1 are considered secure anymore, especially when it comes to hashing data structures (files) or signature generation. Both require that collisions are hard to calculate. – Maarten Bodewes May 08 '17 at 18:51
  • @MaartenBodewes I don't agree with your action. I'm looking for a solution for SHA-1 algorithm. And it would be cool, if someone could share that. – Naloiko Eugene May 22 '19 at 12:09
  • I don't agree. But feel free to vote to reopen (rather than start a discussion in the comments). – Maarten Bodewes May 22 '19 at 21:03

0 Answers0