Swift中使用MD5的正确姿势

在Swift4.0中,无法直接#import CommonCtypto,所以需要桥接OC的CommonCtypto。但是我发现XCode9系统不会自动创建BridgeHeader文件,所以正确的姿势是这样的:

  1. 在项目中创建文件夹CommonCtypto

  2. 在文件夹中新建module.modulemap文件和CommonCryptoHeader.h文件

  3. .modulemap文件中添加代码:

    1
    2
    3
    4
    5
    module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonRandom.h"
    export *
    }
  4. 在CommonCryptoHeader.h中导入CommonCrypto:

    1
    #include <CommonCrypto/CommonCrypto.h>
  5. targets——Build Setting中找到Swift Compiler-Search Paths,在其Import Paths中添加CommCrypto文件夹的路径:$(SRCROOT)/ProjectName/CommonCrypt

  6. 在写MD5的文件里import CommonCrypto即可。

MD5加密的Swift正确写法:

1
2
3
4
5
6
7
8
9
10
11
12
func md5String() ->String!{
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(self, strLen, result)
let hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize(count: self.count)
return String(format: hash as String)
}

更新:

在Swift4.2中,不能再使用上述方法导入CommonCrypto了,因为Swift4.2可以直接 import CommonCrypto

所以更新到Swift4.2后,需要将上面生成的module.modulemapCommonCryptoHeader.h两个文件删掉,import Paths里的路径也删掉,在创建MD5时import CommonCrypto 就可以了。