String的MD5加密分类
首先创建一个桥接头文件
#import <CommonCrypto/CommonDigest.h>
设置Build Setting -> Swift Compiler - General -> Objective-C Bridging Header为该头文件
String+MD5.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>.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)
}
}
好了,下面是使用分类
let origStr = "Hello world"
print(origStr.md5())//输出:3e25960a79dbc69b674cd4ec67a72c62