Swift MD5加密

來源:互聯網
上載者:User

標籤:poi   func   idg   blog   length   bsp   md5加密   class   capacity   

很多時候我們會用到md5加密,下面是swift 3.0的實現方法:

首先建立橋接檔案 xx-Bridging-Header,方法很多,這裡就不介紹了。

然後在橋接檔案中引入加密庫

#import <CommonCrypto/CommonDigest.h>

 

建立一個 Swift 擴充類檔案 String+Extension

extension String {        /// MD5 加密    ///    /// - Returns: 32 位大寫    func ss_md5() -> String {        let str = self.cString(using: .utf8)        let strLen = CUnsignedInt(self.lengthOfBytes(using: .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.deinitialize()                return String(format: hash as String)    }}

 

使用方法:

let MD5Str = str.ss_MD5()

 

Swift MD5加密

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.