How to use CC_MD5 method in swift language

后端 未结 9 2110
南旧
南旧 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条回答
  • 2020-12-01 03:27

    I did pure Swift implementation of MD5 as part of CryptoSwift project.

    I could copy code here but it uses extensions that are part of this project so it may be useless for copy&paste usage. However you can take a look there and use it.

    0 讨论(0)
  • 2020-12-01 03:29

    Here are some changes I had to make to this code to get it working in Swift 5:

        func md5(inString: String) -> String! {
        let str = inString.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(inString.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        var hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deallocate()
        return String(format: hash as String)
    }
    
    0 讨论(0)
  • 2020-12-01 03:33

    Xcode 6 beta 5 now uses an UnsafeMutablePointer in place of an UnsafePointer. String conversion also requires the format: argument label.

    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)
            var hash = NSMutableString()
            for i in 0..<digestLen {
                hash.appendFormat("%02x", result[i])
            }
            result.destroy()
            return String(format: hash)
        }
    }
    
    0 讨论(0)
提交回复
热议问题