Swift 3 making sha1, sha256 and md5 functions

前端 未结 4 2344
清歌不尽
清歌不尽 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:43

    You'd better use Swift Data in Swift 3.

    Data

    And when working with Data, you need to use withUnsafeBytes(_:) or withUnsafeMutableBytes(_:), where you were using bytes or mutableBytes respectively.

    withUnsafeBytes(_:)

    withUnsafeMutableBytes(_:)

    extension Data {
        func hexString() -> String {
            let string = self.map{Int($0).hexString()}.joined()
            return string
        }
    
        func MD5() -> Data {
            var result = Data(count: Int(CC_MD5_DIGEST_LENGTH))
            _ = result.withUnsafeMutableBytes {resultPtr in
                self.withUnsafeBytes {(bytes: UnsafePointer) in
                    CC_MD5(bytes, CC_LONG(count), resultPtr)
                }
            }
            return result
        }
    
        /*
        ... nearly the same for `SHA1` and `SHA256`.
         */
    }
    
    extension String {
        func hexString() -> String {
            return self.data(using: .utf8)!.hexString()
        }
    
        func MD5() -> String {
            return self.data(using: .utf8)!.MD5().hexString()
        }
    
        /*
        ... nearly the same for `SHA1` and `SHA256`.
         */
    }
    

    I prefer making computed properties than no-argument methods (for relatively light-tasks). You need to fix all parts using them, but you can write something like this:

    extension Int {
        var hexString: String {
            return ...
        }
    }
    extension Data {
        var hexString: String {
            let string = self.map{Int($0).hexString}.joined()
            return string
        }
    
        var MD5: Data {
            var result = Data(count: Int(CC_MD5_DIGEST_LENGTH))
            _ = result.withUnsafeMutableBytes {resultPtr in
                self.withUnsafeBytes {(bytes: UnsafePointer) in
                    CC_MD5(bytes, CC_LONG(count), resultPtr)
                }
            }
            return result
        }
    
        /*
        ... nearly the same for `SHA1` and `SHA256`.
         */
    }
    
    extension String {
        var hexString: String {
            return self.data(using: .utf8)!.hexString
        }
    
        var MD5: String {
            return self.data(using: .utf8)!.MD5.hexString
        }
    
        /*
        ... nearly the same for `SHA1` and `SHA256`.
         */
    }
    

    There may be a quicker fix for your code using NSData, but I recommend you to move to Data in Swift 3.

提交回复
热议问题