gpt4 book ai didi

ios - 使用 CCHmac() 生成 HMAC swift sdk8.3

转载 作者:搜寻专家 更新时间:2023-10-31 08:27:01 24 4
gpt4 key购买 nike

在 SDK8.3 之前,我是这样生成我的 hmac 的。现在我在 CCHmac() 函数上遇到错误。由于我是初学者,所以我无法弄清楚如何解决它。预先感谢您的帮助!

xcode warning: cannot involke 'CCHmac' with an argument list of type (UInt32, [CChar]?, UInt, [CChar]?, UInt, inout[(CUnsignedChar)]

func generateHMAC(key: String, data: String) -> String {

let cKey = key.cStringUsingEncoding(NSUTF8StringEncoding)
let cData = data.cStringUsingEncoding(NSUTF8StringEncoding)

var result = [CUnsignedChar](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA512), cKey, strlen(cKey!), cData, strlen(cData!), &result)


let hash = NSMutableString()
for var i = 0; i < result.count; i++ {
hash.appendFormat("%02hhx", result[i])
}

return hash as String
}

最佳答案

问题是 strlen 返回一个 UInt,而 CCHmac 的长度参数是 Int

虽然您可以进行一些强制转换,但您也可以只使用两个数组的 count 属性,而不是调用 strlen

func generateHMAC(key: String, data: String) -> String {

var result: [CUnsignedChar]
if let cKey = key.cStringUsingEncoding(NSUTF8StringEncoding),
cData = data.cStringUsingEncoding(NSUTF8StringEncoding)
{
let algo = CCHmacAlgorithm(kCCHmacAlgSHA512)
result = Array(count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)

CCHmac(algo, cKey, cKey.count-1, cData, cData.count-1, &result)
}
else {
// as @MartinR points out, this is in theory impossible
// but personally, I prefer doing this to using `!`
fatalError("Nil returned when processing input strings as UTF8")
}

let hash = NSMutableString()
for val in result {
hash.appendFormat("%02hhx", val)
}

return hash as String
}

关于ios - 使用 CCHmac() 生成 HMAC swift sdk8.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com