CryptoKit 上的 HMAC 更新

Pat*_*uer 3 swift apple-cryptokit

我是 CryptoKit 的新手,我正在努力将此代码从 Node.js 转换为 Swift(使用 CryptoKit)。

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

我在 Swift/CryptoKit 上做的是:

 var hmac = SHA256.hash(data: Data(base64Encoded: key)!)
Run Code Online (Sandbox Code Playgroud)

但我不知道如何处理第二行。在 Ruby 上可以这样完成:

HMAC.digest('sha256', secret, what)
Run Code Online (Sandbox Code Playgroud)

但是 CryptoKit“没有”这个方法,有什么想法吗?

Cou*_*per 7

对于使用 CryptoKit 的 Swift,你可以这样写:

// 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)
Run Code Online (Sandbox Code Playgroud)

最后一行计算您的“消息验证代码”。

您可以将其转换为数据:

let authenticationCodeData = Data(authenticationCode)
Run Code Online (Sandbox Code Playgroud)

并作为 base64 编码的字符串:

let authenticationCodeBase64String = authenticationCodeData.base64EncodedString()
Run Code Online (Sandbox Code Playgroud)

网上有很多来自 Apple 和其他公司的教程。