在objective-c中,我们可以通过以下代码用md5加密字符串
- 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]
- ];
但现在CC_MD5不工作在swift。
如何处理这个。
这是我想出的。它是String的扩展。
不要忘记添加#import< CommonCrypto / CommonCrypto.h>到Xcode创建的ObjC-Swift桥接头。
不要忘记添加#import< CommonCrypto / CommonCrypto.h>到Xcode创建的ObjC-Swift桥接头。
- 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)
- }
- }