使用CCHmac()生成HMAC swift sdk8.3 [英] Generate a HMAC swift sdk8.3 using CCHmac()

查看:916
本文介绍了使用CCHmac()生成HMAC swift sdk8.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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警告:不能使用类型的参数列表(UInt32,[CChar])来'CCHmac'? ,UInt,[CChar] ?, UInt,inout [(CUnsignedChar)]

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
}


推荐答案

问题是 strlen 返回 UInt ,而 CCHmac 的长度参数是 Int s。

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

虽然你可以做一些强制,你也可以只使用两个数组的 count 属性,而不是调用 strlen

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
}

这篇关于使用CCHmac()生成HMAC swift sdk8.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆