Implementing HMAC and SHA1 encryption in swift

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

    I have checked the above answers and found it so lengthy.

    Solution: I got third party: IDZSwiftCommonCrypto

    Use pod: pod 'IDZSwiftCommonCrypto'

    and use the following function to achieve desired output:

    func getHMacSHA1(forMessage message: String, key: String) -> String? {
        let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha1, key: key).update(string: message)?.final()
        if let encryptedData = hMacVal {
            let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
            let base64String = decData.base64EncodedString(options: .lineLength64Characters)
            print("base64String: \(base64String)")
            return base64String
        } else {
            return nil
        }
    }
    

    For check the result use following website:

    https://hash.online-convert.com/sha1-generator

    Tested in Swift 4.0

提交回复
热议问题