Implementing HMAC and SHA1 encryption in swift

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

    In Swift 4 You need library CommonCrypto https://forums.developer.apple.com/thread/46477

    #import 
    

    And you can create extension with base64

    extension String {
        func hmac(key: String) -> String {
            var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key, key.count, self, self.count, &digest)
            let data = Data(bytes: digest)
            return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
        }
    }
    

    Usege:

    print("HMAC_SHA256:".hmac(key: "MyKey"))
    

    Result:

    6GM2evJeNZYdP3OjPcKmg8TDzILSQAjy4NGhCHnBH5M=
    

提交回复
热议问题