很多時(shí)候我們會(huì)用到md5
加密冻记,下面是swift 3.0
的實(shí)現(xiàn)方法:
首先新建橋接文件xx-Bridging-Header
秉溉,方法很多袍冷,最簡(jiǎn)單的辦法是在swift
工程中任意新建一個(gè)oc
文件念秧,然后會(huì)自動(dòng)提示創(chuàng)建鸽心。
然后在橋接文件中引入加密庫(kù)
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import <CommonCrypto/CommonDigest.h>
加密拓展類為StringMd5.swift
import Foundation
extension String {
func md5() -> String {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.init(allocatingCapacity: 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)
}
}
接下來(lái)只需要調(diào)用就可以了:
let md5String = someString.md5()
資料:
[http://stackoverflow.com/questions/28310589/decode-a-string-in-swift]
[http://stackoverflow.com/questions/24123518/how-to-use-cc-md5-method-in-swift-language]