Last active
April 3, 2018 10:42
-
-
Save akofman/aba0997dbe4e80f518af to your computer and use it in GitHub Desktop.
Swift helper to convert a string or a file to a md5sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MD5{ | |
static func stringSum(string: String) -> String { | |
var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) | |
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { | |
CC_MD5(data.bytes, CC_LONG(data.length), &digest) | |
} | |
var digestHex = "" | |
for index in 0..<Int(CC_MD5_DIGEST_LENGTH) { | |
digestHex += String(format: "%02x", digest[index]) | |
} | |
return digestHex | |
} | |
static func fileSum(path: String) -> String { | |
var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) | |
let handle: NSFileHandle? = NSFileHandle(forReadingAtPath: path) | |
let md5 = UnsafeMutablePointer<CC_MD5_CTX>.alloc(1) | |
CC_MD5_Init(md5) | |
while (true) { | |
let fileData = handle!.readDataOfLength(4096) | |
CC_MD5_Update(md5, fileData.bytes, CC_LONG(fileData.length)); | |
if fileData.length == 0 { | |
break | |
} | |
} | |
CC_MD5_Final(&digest, md5) | |
md5.dealloc(1) | |
var digestHex = "" | |
for index in 0..<Int(CC_MD5_DIGEST_LENGTH) { | |
digestHex += String(format: "%02x", digest[index]) | |
} | |
return digestHex | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When i was trying to use your function in my Custom Swift Framework, i get these errors. Would you like to tell me how to get ride of them.
Use of unresolved identifier 'CC_LONG'
Use of unresolved identifier 'CC_MD5_DIGEST_LENGTH'
Use of unresolved identifier 'CC_MD5'