in Objective-c, we can hash a string like this:
const char *cStr = [someString UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result );
m
I did pure Swift implementation of MD5 as part of CryptoSwift project.
I could copy code here but it uses extensions that are part of this project so it may be useless for copy&paste usage. However you can take a look there and use it.
Here are some changes I had to make to this code to get it working in Swift 5:
func md5(inString: String) -> String! {
let str = inString.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(inString.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.deallocate()
return String(format: hash as String)
}
Xcode 6 beta 5 now uses an UnsafeMutablePointer
in place of an UnsafePointer
. String conversion also requires the format:
argument label.
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)
}
}