Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a HMAC swift sdk8.3 using CCHmac()

Tags:

ios

swift

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
}
like image 242
Jab Avatar asked Apr 22 '15 13:04

Jab


1 Answers

The problem is that strlen returns a UInt, while CCHmac’s length arguments are Ints.

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
}
like image 52
Airspeed Velocity Avatar answered Sep 29 '22 06:09

Airspeed Velocity