Skip to content

Instantly share code, notes, and snippets.

@akofman
Last active April 3, 2018 10:42
Show Gist options
  • Save akofman/aba0997dbe4e80f518af to your computer and use it in GitHub Desktop.
Save akofman/aba0997dbe4e80f518af to your computer and use it in GitHub Desktop.
Swift helper to convert a string or a file to a md5sum
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
}
}
@iosdeveloper480
Copy link

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'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment