在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 }