I'm creating the MD5
checksum on video files before uploading to the server. I'm running into a case where when I upload the same file, a different MD5
checksum is generated.
I use the following code for generating the checksum
static func md5File(url: URL) -> String? {
let bufferSize = 1024 * 1024
do {
// Open file for reading:
let file = try FileHandle(forReadingFrom: url)
defer {
file.closeFile()
}
// Create and initialize MD5 context:
var context = CC_MD5_CTX()
CC_MD5_Init(&context)
// Read up to `bufferSize` bytes, until EOF is reached, and update MD5 context:
while case let data = file.readData(ofLength: bufferSize), data.count > 0 {
data.withUnsafeBytes {
_ = CC_MD5_Update(&context, $0, CC_LONG(data.count))
}
}
// Compute the MD5 digest:
var digest = Data(count: Int(CC_MD5_DIGEST_LENGTH))
digest.withUnsafeMutableBytes {
_ = CC_MD5_Final($0, &context)
}
let stringDigest = digest.map { String(format: "%02hhx", $0) }.joined()
return stringDigest
} catch {
return nil
}
}
I do notice the iOS does compressing after the video file is selected, then I'm given a URL in the tmp/
directory. The file each time does have the same size, but a different filename. It is my understanding the MD5
isn't calculated based on the filename. Am I correct with this? What could be causing a different MD5
every time?