Before SDK8.3 I was generating my hmac this way. Now I get an error on the CCHmac() function. Since I'm a beginner I can't figure out how to fix it. Thanks in advance for your help!
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
}
The problem is that strlen
returns a UInt
, while CCHmac
’s length arguments are Int
s.
While you could do some coercion, you may as well just use the count
property of the two arrays rather than calling 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
}
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