微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐