Created
August 10, 2014 16:59
-
-
Save pietbrauer/2205b5c9986a9d886b00 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 { | |
func MD5() -> NSString { | |
let digestLength = Int(CC_MD5_DIGEST_LENGTH) | |
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength) | |
CC_MD5(bytes, CC_LONG(length), md5Buffer) | |
var output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2)) | |
for i in 0..<digestLength { | |
output.appendFormat("%02x", md5Buffer[i]) | |
} | |
return NSString(format: output) | |
} | |
} | |
extension NSString { | |
func MD5() -> NSString { | |
let digestLength = Int(CC_MD5_DIGEST_LENGTH) | |
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength) | |
CC_MD5(UTF8String, CC_LONG(strlen(UTF8String)), md5Buffer) | |
var output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2)) | |
for i in 0..<digestLength { | |
output.appendFormat("%02x", md5Buffer[i]) | |
} | |
return NSString(format: output) | |
} | |
} |
@longxianlin Add: #import <CommonCrypto/CommonCrypto.h>
to the ObjC-Swift bridging header that Xcode creates.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what CC_MD5_DIGEST_LENGTH?