Swift scripting and CommonCrypto

Hi,

I am writing a swift build script for my app which needs to calculate md5 checksum of a string. The issue I am facing is I am unable to link to CommonCrypto so i can use CC's functions. Any advice would be helpful.

P.S. My script looks something like this


#!/usr/bin/swift
import Foundation
import Darwin

/*
... code code code
*/

// Here we get a compile error CC_MD5_DIGEST_LENGTH & CC_MD5 are unresolved udentifiers
extension String {
    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!, strLen, result)
     
        let hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
     
        result.destroy()
     
        return String(format: hash as String)
    }
}

AFAIK, CommonCrypto is not included in the Darwin module. I have successfully used the following method for system headers that are not in the Darwin module.


You can create a modulemap for CommonCrypto so that you can import it.


Create a directory (e.g. CommonCrypto) in a location of your choice. Inside the directory, create a file called

module.modulemap
with the following contents:
module CommonCrypto [system] [extern_c] {
  umbrella "/usr/include/CommonCrypto"
  export *
}

Change the first line of your script to

#!/usr/bin/swift -I module-dir
. Replace
module-dir
with the path to the directory you created that contains the module map file.


You can read more about modules here.

Hi,


In your bridging-header ([YourProjectName]-Bridging-Header.h), just import <CommonCrypto/CommonCrypto.h>:


//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import <CommonCrypto/CommonCrypto.h> // required for MD5


To create a bridging-header if you don't already have one:

The easy way

  • File > New > File...
  • Choose Objective-C File.
  • Give it a name and click on "Finish".
  • Click on the "Create Bridging Header" button in the dialog box.
  • Eventually, remove the temporary Objective-C file.
  • The manual way

  • Add a header file to your project, named [YourProjectName]-Bridging-Header.h.
  • In your project build settings, find Swift Compiler – Code Generation, and next to Objective-C Bridging Header, add the path to your bridging header file, from the project’s root folder.
  • running a sub process to caculate checksum may be better?

    Swift scripting and CommonCrypto
     
     
    Q