-
-
Save samsonjs/bbbfbb5316acc027c1978673b20f6bfa to your computer and use it in GitHub Desktop.
NSString & NSData to MD5
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
import Foundation | |
extension NSData { | |
var md5: NSString { | |
let digestLength = Int(CC_MD5_DIGEST_LENGTH) | |
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLength) | |
CC_MD5(bytes, CC_LONG(length), md5Buffer) | |
let output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2)) | |
for i in 0..<digestLength { | |
output.appendFormat("%02x", md5Buffer[i]) | |
} | |
return NSString(format: output) | |
} | |
} | |
extension Data { | |
var md5: String { | |
return (self as NSData).md5 as String | |
} | |
} | |
extension NSString { | |
var md5: NSString { | |
let digestLength = Int(CC_MD5_DIGEST_LENGTH) | |
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLength) | |
CC_MD5(utf8String, CC_LONG(strlen(utf8String)), md5Buffer) | |
let output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2)) | |
for i in 0..<digestLength { | |
output.appendFormat("%02x", md5Buffer[i]) | |
} | |
return NSString(format: output) | |
} | |
} | |
extension String { | |
var md5: String { | |
return (self as NSString).md5 as String | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment