swift使用md5算法:
1.新建一个桥接头文件Objective-CBridgingHeader.h,内容如下:
#ifndef QueryPhoneNumber_Objective_CBridgingHeader_h
#define QueryPhoneNumber_Objective_CBridgingHeader_h
#import <CommonCrypto/CommonHMAC.h>
#endif
2.工程属性 -> Build Settings -> All -> Levels ->
Swift Compiler - Code Generation -> Objective-C Bridging Header ->双击后面空行在弹出框里输入:
Objective-CBridgingHeader.h, 如图:
3.扩展String
import Foundation
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 as String)
}
}