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?