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

十年热恋 提交于 2019-12-21 05:35:38

问题


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))


回答1:


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
}



回答2:


A solution for Swift 4.1:

import CommonCrypto

extension Data
{
    func md5() -> Data
    {
        var digest = Data(count: Int(CC_MD5_DIGEST_LENGTH))

        self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) -> Void in
            digest.withUnsafeMutableBytes { (mutableBytes : UnsafeMutablePointer<UInt8>) -> Void in
                CC_MD5(bytes, CC_LONG(self.count), mutableBytes)
            }
        }

        return digest
    }
}

See Importing CommonCrypto in a Swift framework for the CommonCrypto part.



来源:https://stackoverflow.com/questions/31964291/how-to-get-md5-hash-from-string-in-swift-and-make-bridge-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!