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

在SDK8.3之前我用这种方式生成了我的hmac.现在我在CCHmac()函数上出错了.由于我是初学者,我无法弄清楚如何解决它.在此先感谢您的帮助!

xcode warning: cannot involke ‘CCHmac’ with an argument list of type (UInt32,[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的长度参数是Ints.

虽然你可以做一些强制,你也可以只使用两个数组的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.count-1,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
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...