如何解决CryptoKit 上的 HMAC 更新
我是 CryptoKit 的新手,我正在努力将这段代码从 Node.js 转换为 Swift(使用 CryptoKit)。
// create a sha256 hmac with the secret
var hmac = crypto.createHmac('sha256',key);
return hmac.update(what).digest('base64');
我在 Swift/CryptoKit 上所做的是:
var hmac = SHA256.hash(data: Data(base64Encoded: key)!)
但我不知道如何处理第二行。在 Ruby 上,它可以通过这种方式完成:
HMAC.digest('sha256',secret,what)
但是CryptoKit“没有”这种方法,有什么想法吗?
解决方法
使用 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)
最后一行计算您的“消息验证码”。
您可以将其转换为数据:
let authenticationCodeData = Data(authenticationCode)
并作为 base64 编码的字符串:
let authenticationCodeBase64String = authenticationCodeData.base64EncodedString()
网络上有很多来自 Apple 和其他公司的教程。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。