1、創建橋街頭文件
首先,我們需要建立Swift與Objective-C的橋街頭文件,詳細建立過程請點擊以下鏈接:
基於Swift的iOS應用程序開發:創建Swift與Objective-C之間的橋街頭文件
2、引入Objective-C庫
#import <CommonCrypto/CommonDigest.h>
3、編寫加密方法
func md5String(strIn:String) ->String{
let str = strIn.cString(using: String.Encoding.utf8)
let strLen = CC_LONG(strIn.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen);
CC_MD5(str!, strLen, result);
let hash = NSMutableString();
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i]);
}
result.deinitialize();
return String(format: hash as String)
}