Search code examples
swifthashcryptoswift

Get hash from file using CryptoSwift


So I try to get the hash from a file. Using the CryptoSwift library. The truth is the variable with the hash that I got from the VLC website, so that should be true. However, the hash I generate is different from the hash I know to be the truth.

Which step do I miss?

Code:

let filePath = "/Users/pjc/Desktop/vlc-3.0.0.dmg"

let fileURL = URL(fileURLWithPath: filePath)
let truth = "e6f7179cb06809b6101803da3ac4191edb72ecf82f31b8ae7dbf010e1a78ba26"

do {
   let fileData = try Data.init(contentsOf: fileURL)
   print(fileData)
   let fileBytes = fileData.bytes
   let hash = fileBytes.sha256()
   print(hash.debugDescription)

} catch {

   //handle error
   print(error)
}

print(hash)
print(truth)

Log:

fileData: 46818658 bytes
hash.debugDescription: [230, 247, 23, 156, 176, 104, 9, 182, 16, 24, 3, 218, 58, 196, 25, 30, 219, 114, 236, 248, 47, 49, 184, 174, 125, 191, 1, 14, 26, 120, 186, 38]
hash: 105553117580736
truth: e6f7179cb06809b6101803da3ac4191edb72ecf82f31b8ae7dbf010e1a78ba26

Solution

  • [230, 247, 23, 156, 176, 104, 9, 182, 16, 24, 3, 218, 58, 196, 25, 30, 219, 114, 236, 248, 47, 49, 184, 174, 125, 191, 1, 14, 26, 120, 186, 38]
    

    and

    e6f7179cb06809b6101803da3ac4191edb72ecf82f31b8ae7dbf010e1a78ba26
    

    are just two different representations of the same hash value: The first as an array of integers, the second as a string with the hexadecimal representation of the bytes.

    The .toHexString() method of the CryptoSwift library creates a hex string from the array, therefore

    print(hash.toHexString())
    

    should produce the expected result.