Swift 3 making sha1, sha256 and md5 functions

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

    I find most of the answer ok, but if we should have a true universal solution I think we need to step it up a level.

    CC_LONG is just an UInt32 and will not support really large data structures.

    This is my solution in Swift 3:

    First we create a foundation that work with Data:

    struct Sha256 {
        let context = UnsafeMutablePointer.allocate(capacity:1)
    
        init() {
            CC_SHA256_Init(context)
        }
    
        func update(data: Data) {
            data.withUnsafeBytes { (bytes: UnsafePointer) -> Void in
                let end = bytes.advanced(by: data.count)
                for f in sequence(first: bytes, next: { $0.advanced(by: Int(CC_LONG.max)) }).prefix(while: { (current) -> Bool in current < end})  {
                    _ = CC_SHA256_Update(context, f, CC_LONG(Swift.min(f.distance(to: end), Int(CC_LONG.max))))
                }
            }
        }
    
        func final() -> Data {
            var digest = [UInt8](repeating: 0, count:Int(CC_SHA256_DIGEST_LENGTH))
            CC_SHA256_Final(&digest, context)
    
            return Data(bytes: digest)
        }
    }
    

    For convenience we do an extension for Data:

    extension Data {
        func sha256() -> Data {
            let s = Sha256()
            s.update(data: self)
            return s.final()
        }
    }
    

    And last an extension for String:

    extension String {
        func sha256() -> Data {
            return self.data(using: .utf8)!.sha256()
        }
    }
    

    If needed, convert the result from Data to hex string or something else depending on your use case.

    This solution can be used for Sha512, MD5 etc. to get true universal solutions with Apple's CommonCrypto that are easy to extend to many different use cases.

提交回复
热议问题