Implementing HMAC and SHA1 encryption in swift

后端 未结 8 1339
借酒劲吻你
借酒劲吻你 2020-11-29 01:42

I am relatively new to Swift and i\'m stuck encrypting using HMAC and SHA1. I Found the following answer https://stackoverflow.com/a/24411522/4188344 but i can\'t work out h

8条回答
  •  佛祖请我去吃肉
    2020-11-29 02:27

    If you want the same result in hexadecimal format, you can use the following extension:

    extension String {
        func hmac(algorithm: HMACAlgorithm, key: String) -> String {
            let cKey = key.cStringUsingEncoding(NSUTF8StringEncoding)
            let cData = self.cStringUsingEncoding(NSUTF8StringEncoding)
            var result = [CUnsignedChar](count: Int(algorithm.digestLength()), repeatedValue: 0)
            let length : Int = Int(strlen(cKey!))
            let data : Int = Int(strlen(cData!))
            CCHmac(algorithm.toCCHmacAlgorithm(), cKey!,length , cData!, data, &result)
    
            let hmacData:NSData = NSData(bytes: result, length: (Int(algorithm.digestLength())))
    
            var bytes = [UInt8](count: hmacData.length, repeatedValue: 0)
            hmacData.getBytes(&bytes, length: hmacData.length)
    
            var hexString = ""
            for byte in bytes {
                hexString += String(format:"%02hhx", UInt8(byte))
            }
            return hexString
        }
    }
    

提交回复
热议问题