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

只愿长相守 提交于 2019-12-03 21:14:27

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
}

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.

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