How to get MD5 hash from string in SWIFT and make bridge-header

10,010

You need to add a bridging header and add the #import <CommonCrypto/CommonCrypto.h> statement to it.

The easiest way to add a bridging header is to add an Objective-C file to the project, you will be aked ig you want to add a bridging header, reply yes. After that you can delete the Objective-C file file that was added.

Example code:

func md5(#string: String) -> NSData {
    var digest = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))!
    if let data :NSData = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_MD5(data.bytes, CC_LONG(data.length),
            UnsafeMutablePointer<UInt8>(digest.mutableBytes))
    }
    return digest
}

//Test:
let digest = md5(string:"Here is the test string")
println("digest: \(digest)")

Output:

digest: 8f833933 03a151ea 33bf6e3e bbc28594

Here is a more Swift 2.0 version returning an array of UInt8:

func md5(string string: String) -> [UInt8] {
    var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_MD5(data.bytes, CC_LONG(data.length), &digest)
    }

    return digest
}
Share:
10,010
Mike
Author by

Mike

Student

Updated on June 04, 2022

Comments

  • Mike
    Mike about 2 years

    i dont even expect this problem, but it appears. I try to get md5 hash from string in swift. I search about that on SO and assume that i need to import library like that:

    #import <CommonCrypto/CommonCrypto.h>
    

    First of all compiler said that '#' is not okay. Then i removed and compiler said that '<' is not okay. I tried to figure out that and find recommendations to add folder named "CommonCrypto" and create a file named "module.map". I cant understand how to create file with this extension. Okay, i create swift file and replace its extension. Then write code there:

    module CommonCrypto [system] {
        header "/usr/include/CommonCrypto/CommonCrypto.h"
        export *
    }
    

    and again its not okay Then in recommendations was adding the new module to Import Paths under Swift Compiler – Search Paths in your project settings ${SRCROOT}/CommonCrypto).

    and its again not okay.

    i cant belive that its so difficult to do that. i think i misunderstand some steps or something. if you know step by step answer please help))