How to use CC_MD5 method in swift language

后端 未结 9 2145
南旧
南旧 2020-12-01 02:52

in Objective-c, we can hash a string like this:

const char *cStr = [someString UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result );
m         


        
9条回答
  •  萌比男神i
    2020-12-01 03:08

    So here is the Solution and I know It will save your time 100%

    BridgingHeader - > Used to Expose Objective-c code to a Swift Project

    CommonCrypto - > is the file needed to use md5 hash

    Since Common Crypto is a Objective-c file, you need to use BridgingHeader to use method needed for hashing


    (e.g)

    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.alloc(digestLen)
        CC_MD5(str!, strLen, result)
        var hash = NSMutableString()
        for i in 0..

    }

    How to add Common Crypto into a Swift Project??

    This link will teach you how (STEP by STEP).

    I recommend using Bridging Header

    *************Updated Swift 3****************

    extension String {
    func toMD5()  -> String {
    
            if let messageData = self.data(using:String.Encoding.utf8) {
                var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
    
                _ = digestData.withUnsafeMutableBytes {digestBytes in
                    messageData.withUnsafeBytes {messageBytes in
                        CC_MD5(messageBytes, CC_LONG((messageData.count)), digestBytes)
                    }
                }
                return digestData.hexString()
            }
    
            return self
        }
    }
    
    
    extension Data {
    
        func hexString() -> String {
            let string = self.map{ String($0, radix:16) }.joined()
            return string
        }
    
    }
    

    How to use?

    let stringConvertedToMD5 = "foo".toMD5()

提交回复
热议问题