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 ); md5String = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ];
But CC_MD5 doesn't work in Swift. How do we deal with this?
This is what I came up with. It's an extension to String. Don't forget to add #import <CommonCrypto/CommonCrypto.h>
to the ObjC-Swift bridging header that Xcode creates.
extension String { var md5: String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.dealloc(digestLen) return String(format: hash as String) } }
Here's my version in Swift 3.0, I believe it to be safer and faster than the other answers here.
A bridging header with #import <CommonCrypto/CommonCrypto.h>
is required.
func MD5(_ string: String) -> String? { let length = Int(CC_MD5_DIGEST_LENGTH) var digest = [UInt8](repeating: 0, count: length) if let d = string.data(using: String.Encoding.utf8) { _ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in CC_MD5(body, CC_LONG(d.count), &digest) } } return (0..<length).reduce("") { $0 + String(format: "%02x", digest[$1]) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With