How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS?

后端 未结 6 1957
臣服心动
臣服心动 2020-11-27 10:32

The Security services API doesn\'t appear to allow me to compute a hash directly. There are plenty of public domain and liberally licensed versions available, but I\'d rathe

6条回答
  •  孤独总比滥情好
    2020-11-27 11:18

    This is what worked for me

    func sha256(securityString : String) -> String {
        let data = securityString.dataUsingEncoding(NSUTF8StringEncoding)!
        var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
        CC_SHA256(data.bytes, CC_LONG(data.length), &hash)
        let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
        for byte in hash {
            output.appendFormat("%02x", byte)
        }
        return output as String
    }
    

提交回复
热议问题