So here is the Solution and I know It will save your time 100%
BridgingHeader
- > Used to Expose Objective-c code to a Swift Project
CommonCrypto
- > is the file needed to use md5 hash
Since Common Crypto is a Objective-c file, you need to use BridgingHeader to use method needed for hashing
(e.g)
extension String {
func md5() -> String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash as String)
}
}
How to add Common Crypto into a Swift Project??
This link will teach you how (STEP by STEP).
I recommend using Bridging Header
*************Updated Swift 3****************
extension String {
func toMD5() -> String {
if let messageData = self.data(using:String.Encoding.utf8) {
var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes {digestBytes in
messageData.withUnsafeBytes {messageBytes in
CC_MD5(messageBytes, CC_LONG((messageData.count)), digestBytes)
}
}
return digestData.hexString()
}
return self
}
}
extension Data {
func hexString() -> String {
let string = self.map{ String($0, radix:16) }.joined()
return string
}
}
How to use?
let stringConvertedToMD5 = "foo".toMD5()