-1

I need help with making a signature in swift 3 with HMAC SHA1 for a web request. I have an example in Java but really do not know how to do it in swift.

Java formula:

signature = Base64.encode(HMAC_SHA1.digest(data,Base64.decode(client_secret))

signature = +t2GOKtZt1hU+C7OGBKZbDOKxds=
  • 2
    Possible duplicate of [Implementing HMAC and SHA1 encryption in swift](https://stackoverflow.com/questions/26970807/implementing-hmac-and-sha1-encryption-in-swift) – shallowThought Jun 13 '17 at 12:01

3 Answers3

0

Solution:

extension Data {

    func hmacsha1(key: String) -> String? {
        guard let keyData = Data(base64Encoded: key, options: .ignoreUnknownCharacters) else {
            return nil
        }
        var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
        self.withUnsafeBytes({ dataBytes in
            keyData.withUnsafeBytes({ keyDataBytes in
                CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), keyDataBytes, keyData.count, dataBytes, self.count, &digest)
            })
        })
        return Data(bytes: digest).base64EncodedString()
    }

}

Test:

    let data = Data("Test".utf8)
    let key = Data("Key".utf8).base64EncodedString()
    let hmac = data.hmacsha1(key: key)

Result: "xIcCRlnXa+IqFtO+9AF3OqeRdAU="

sundance
  • 2,930
  • 1
  • 20
  • 25
  • Hi, when I use your solution with Data ` "3tme3bnmepmibhvv1toq4xfed866faaa06aa1b13979653502956" ` and key ` "0gkp7n6tnwdn816kyzfp26s3e" ` i ve got this ` 'result = zWYYH5p8jUn6cAHjP+oB6IbOUuU= ` but i need ` 1WVoLPXcqJVKaxSK50ArFHtKtnM= `. maybe its becouse its not decoding like in java example? ` Base64.decode(client_secret) ` – Aleksandr Sabri Jun 13 '17 at 17:37
  • Sorry, I had a typo in my code. I used `keyData.count` twice in the line with `CCHmac`. I adapted my answer accordingly. Now, everything should work. – sundance Jun 14 '17 at 11:51
  • i solved a problem, thanks for your help if u interested I add a code snippet – Aleksandr Sabri Jun 18 '17 at 21:36
0

swift 3 : first convert the image into data.Then convert this imageData to base64 string.

      imgData = UIImageJPEGRepresentation(image, 0.9)! as Data
    strBase64 = imgData.base64EncodedString(options: .lineLength64Characters) as NSString

then use this base64 string wherever you want.

Tanvir Nayem
  • 702
  • 10
  • 25
0

Problem solved

extension String {
    func hmac(algorithm: kCCHmacAlgSHA1, key: NSData) -> String {
        let cKey = key
        let cData = self.cString(using: String.Encoding.ascii)
        var cHMAC = [CC_SHA1_DIGEST_LENGTH]
        CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey.bytes, cKey.length, cData, Int(strlen(cData!)), &cHMAC)
        let hmacData:NSData = NSData(bytes: cHMAC, length: cHMAC)
        let hmacBase64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        return String(hmacBase64)
    }
}

let hmacResult: String = cData.hmac(algorithm: HMACAlgorithm.SHA1, key: keyData)