在 SDK8.3 之前,我是通过这种方式生成 hmac 的。现在我在 CCHmac() 函数上遇到错误。由于我是初学者,我不知道如何解决它。在此先感谢您的帮助!
xcode 警告:无法使用类型为 (UInt32, [CChar]?, UInt, [CChar]?, UInt, inout[(CUnsignedChar)] 的参数列表调用“CCHmac”
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
, while CCHmac
的长度参数是Int
s.
虽然您可以进行一些强制,但您也可以使用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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)