很多时候我们会用到md5
加密,下面是swift 3.0
的实现方法:
首先新建桥接文件xx-Bridging-Header
,方法很多,最简单的办法是在swift
工程中任意新建一个oc
文件,然后会自动提示创建。
然后在桥接文件中引入加密库
//
// 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)
}
}
接下来只需要调用就可以了:
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]