Swift 3 making sha1, sha256 and md5 functions

前端 未结 4 2343
清歌不尽
清歌不尽 2021-02-20 07:05

In Swift 2, I used the following code to extend string variables and to be able to make sha1, sha256, and md5.

After moving to swift 3, the code is not working any more!

4条回答
  •  时光取名叫无心
    2021-02-20 07:36

    For completion, the shortest and most flexible solution in Swift 4 is:

    extension Data {
    
        var hexString: String {
            return map { String(format: "%02hhx", $0) }.joined()
        }
    
        var md5: Data {
            var digest = [Byte](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
            self.withUnsafeBytes({
                _ = CC_MD5($0, CC_LONG(self.count), &digest)
            })
            return Data(bytes: digest)
        }
    
        var sha1: Data {
            var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
            self.withUnsafeBytes({
                _ = CC_SHA1($0, CC_LONG(self.count), &digest)
            })
            return Data(bytes: digest)
        }
    
        var sha256: Data {
            var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
            self.withUnsafeBytes({
                _ = CC_SHA256($0, CC_LONG(self.count), &digest)
            })
            return Data(bytes: digest)
        }
    
    }
    
    extension String {
    
        var md5: Data {
            return self.data(using: .utf8)!.md5
        }
    
        var sha1: Data {
            return self.data(using: .utf8)!.sha1
        }
    
        var sha256: Data {
            return self.data(using: .utf8)!.sha256
        }
    
    }
    

提交回复
热议问题