0

I have some code to generate MD5 String from file data:

extension Data {

func hexString() -> String {
    let string = self.map{ String($0, radix:16) }.joined()

    // "45769ca7ec1ac00cec11df87df982b7d"
    return string
}

func MD5() -> Data {
    var result = Data(count: Int(CC_MD5_DIGEST_LENGTH))
    _ = result.withUnsafeMutableBytes {resultPtr in
        self.withUnsafeBytes {(bytes: UnsafePointer<UInt8>) in
            CC_MD5(bytes, CC_LONG(count), resultPtr)
        }
    }
    return result
}
}

extension String {
    func hexString() -> String {
        return self.data(using: .utf8)!.hexString()
    }

    func MD5() -> String {
        return self.data(using: .utf8)!.MD5().hexString()
    }
}

I'm not sure if this is working, as it could just be the MD5 string I am getting from Vimeo is wrong.

Firstly, does that Swift 3 code look ok for generating MD5? Usage:

let fileHandle = try? FileHandle(forReadingFrom: getFileUrl(forFileId: id)!)
let fileData = fileHandle?.availableData
if let md5 = fileData?.MD5().hexString() { ... }

Secondly, is there a web tool I can use to upload my file and get its MD5 String back?

UPDATE: I tested my file in the online MD5 tool and I get the following hash: F0750875A790471702E9D2D34433729A But my code produces this: f075875a79047172e9d2d34433729a

It seems so close! It must be something in my extension. Is there a better MD5 solution in Swift 3?

Lee Probert
  • 10,308
  • 8
  • 43
  • 70

1 Answers1

0

Ok. I found a good solution:

extension Data {

var md5String:String {

    var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))

    var digestHex = ""
    self.withUnsafeBytes { (bytes: UnsafePointer<CChar>) -> Void in

        CC_MD5(bytes, CC_LONG(self.count), &digest)
        for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
            digestHex += String(format: "%02x", digest[index])
        }
    }
    return digestHex
  }

}

This is a computed variable on a Data Extension. I've tested this and it produces correct MD5 hash strings. You can also use it on a String extension like so:

extension String {

func MD5() -> String {
    return self.data(using: .utf8)!.md5String
}
}
Lee Probert
  • 10,308
  • 8
  • 43
  • 70