简体   繁体   中英

HMAC 256 Signature in Swift 5 with CryptoKit

What is the most updated way to get a HMAC 256 signature using CryptoKit and Swift 5? After trying different methods mentioned on HMAC SHA256 in Swift 4 and Implementing HMAC and SHA1 encryption in swift I still haven't been able to make the API request work. These two methods give me a different signature:

Using CryptoKit

import CryptoKit

let urlWithoutSignature = "https://api.binance.com/sapi/v1/capital/config/getall?timestamp=\(timeStamp)"
let secretString = "p23842nll3vc8vdfnsddfiupsd8cvsnlsdfs"
let key = SymmetricKey(data: secretString.data(using: .utf8)!)
let signature = HMAC<SHA256>.authenticationCode(for: urlWithoutSignature.data(using: .utf8)!, using: key)

let signatureString = Data(signature).map { String(format: "%02hhx", $0) }.joined()

Using a string extension

 import CommonCrypto
    
    let signatureString = urlWithoutSignature.hmac(key: secretString))
    
 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))
     }
  }

How can I check that the signatures are correct? I can't compare them with the Postman one because the timestamp is always different.
The API docs

let signatureString = Data(signature).base64EncodedString()

is equal to CommonCrypto's signatureString.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM