HMAC update on CryptoKit

1.7k Views Asked by At

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?

1

There are 1 best solutions below

3
On

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.