swift md5

作者: 会飞的大西瓜v | 来源:发表于2018-04-11 15:17 被阅读8次
    extension String  {
        var md5: String! {
            let str = self.cString(using:String.Encoding.utf8)
            let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
            let digestLen = Int(CC_MD5_DIGEST_LENGTH)
            let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
            
            CC_MD5(str!, strLen, result)
            
            let hash = NSMutableString()
            for i in 0..<digestLen {
                hash.appendFormat("%02x", result[i])
            }
            
            result.deallocate()
            
            return String(format: hash as String)
        }
    }
    
    extension NSData {
        
        func MD5() -> NSString {
            let digestLength = Int(CC_MD5_DIGEST_LENGTH)
            let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLength)
            CC_MD5(bytes, CC_LONG(length), md5Buffer)
            let output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2))
            for i in 0..<digestLength {
                output.appendFormat("%02x", md5Buffer[i])
            }
            
            return NSString(format: output)
        }
    }
    

    相关文章

      网友评论

          本文标题:swift md5

          本文链接:https://www.haomeiwen.com/subject/crfzhftx.html