Implementing HMAC and SHA1 encryption in swift

后端 未结 8 1343
借酒劲吻你
借酒劲吻你 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:05

    Here is how to create a Swift 4 extension:

    Bridging headers file

    #import 
    

    Code

    extension String {
    
        func hmac(key: String) -> String {
            var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), key, key.count, self, self.count, &digest)
            let data = Data(bytes: digest)
            return data.map { String(format: "%02hhx", $0) }.joined()
        }
    
    }
    

    Example

    let result = "test".hmac(key: "test")
    

    Result

    0c94515c15e5095b8a87a50ba0df3bf38ed05fe6
    

提交回复
热议问题