美文网首页
Swift5.0 MD5加密

Swift5.0 MD5加密

作者: WMSmile | 来源:发表于2020-11-17 11:37 被阅读0次
    import CommonCrypto
    public extension String {
        /* ################################################################## */
        /**
         - returns: the String, as an MD5 hash.
         */
        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 hash as String
        }
    }
    

    使用

    let needStr = "1234"
    let md5Str = needStr.md5
    print("\(md5Str)")
    

    打印 827ccb0eea8a706c4c34a16891f84e7b

    相关文章

      网友评论

          本文标题:Swift5.0 MD5加密

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