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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With