ksnowlv

回顾过去,总结以往;立足现在,铭记当下;技术为主,笔记而已.

Swift-散列算法md5

| Comments

swift中散列算法md5很常用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    func md5() -> NSString {

        guard self.length > 0 else {
            return self
        }

        let utf8Buf = self.cString(using: String.Encoding.utf8.rawValue)
        let length = self.lengthOfBytes(using: String.Encoding.utf8.rawValue)

        let buffer = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: Int(CC_MD5_DIGEST_LENGTH))
        buffer.initialize(to: 0)
        CC_MD5(utf8Buf,CC_LONG(length), buffer)

        let md5String = NSMutableString()

        for i in 0 ..< CC_MD5_DIGEST_LENGTH {
            md5String.appendFormat("%02x", buffer[Int(i)])
        }

        buffer.deallocate()

        return md5String.uppercased as NSString
    }

记得在bridging-header中导入头文件

  • CommonCrypto/CommonDigest.h

Comments

comments powered by Disqus
Included file 'custom/after_footer.html' not found in _includes directory