使用Swift的方法来加密的时候存在内存泄露的问题,但是在OC上使用就不会出现内存泄露;Swift为何会泄露这个还未知、尽请告知。
(直接正文)
先添加头文件:<CommonCrypto/CommonDigest.h>
OC方式
- (NSString *)md5OC:(NSString *)string {
const char *cStr = [string UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, (int)strlen(cStr), digest);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
Swift方式
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!, UInt32(strLen), result)
let hash = NSMutableString.init(capacity: Int(CC_MD5_DIGEST_LENGTH) * 2)
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return hash as String
}
第三方MD5加密库:CryptoSwift