3

I'm new to CryptoKit, and I'm struggling to translate this code from Node.js to Swift (using CryptoKit).

// create a sha256 hmac with the secret
var hmac = crypto.createHmac('sha256', key);
return hmac.update(what).digest('base64');

What I'm doing on Swift/CryptoKit is:

 var hmac = SHA256.hash(data: Data(base64Encoded: key)!)

but I don't see how to handle the second line. On Ruby it can done on this way:

HMAC.digest('sha256', secret, what)

but CryptoKit "doesn't have" this method, any ideas?

Pataquer
  • 283
  • 1
  • 14

1 Answers1

7

With Swift using CryptoKit you would write this:

// create the prehash string by concatenating required parts
guard let what: Data = (timestampString + methodString + requestPathString + bodyString).data(using: .utf8) else {
    fatalError(...)
}
guard let key: Data = Data(base64Encoded: secret) else {
    fatalError(...)
}
let authenticationCode = HMAC<SHA256>.authenticationCode(for: what, using: key)

The last line computes your "Message Authentication Code".

You can convert this to data:

let authenticationCodeData = Data(authenticationCode)

and as a base64 encoded string:

let authenticationCodeBase64String = authenticationCodeData.base64EncodedString()

There are many tutorials from Apple and others in the web.

CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67
  • My problem is that 'key' is giving by my API provider (https://docs.pro.coinbase.com/?javascript#signing-a-message), and 'what' is the message that is sent. From your example, I wouldn't be using 'key' provided by API. – Pataquer Feb 17 '21 at 20:32
  • According the docs you provided, you need to use the base64 decoded `secret` as the "key" to generate the HMAC. I will update my answer based on the docs. Don't confuse the variable `key` which is the base64 decoded `secret` with the "key" provided by the provider! Otherwise, follow the documentation - which is very good. – CouchDeveloper Feb 18 '21 at 09:04
  • Yeah! Documentation on Coinbase is pretty good, my understanding of CryptoKit is another thing... XD – Pataquer Feb 18 '21 at 09:56