2015-04-22 50 views
2

在SDK8.3之前,我通過這種方式生成了我的hmac。現在我在CCHmac()函數上出現錯誤。由於我是初學者,我無法弄清楚如何解決這個問題。在此先感謝您的幫助!使用CCHmac生成一個HMAC swift sdk8.3()

xcode的警告:不能involke 'CCHmac' 與類型的參數列表(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 
} 
+0

類似(也許有用)的方法在這裏:http://stackoverflow.com/a/25762128/1187415。 –

回答

4

問題是strlen返回UInt,而CCHmac的長度參數是Int秒。

雖然你可以做一些強制,你可能也只是使用這兩個陣列的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, 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 
} 
+0

你又快了:) - 但是請注意,使用'.count'你將包含字符串的終止零,與帶有'strlen()'的原始代碼相比,這會給出不同的結果。但實際上我會將該字符串轉換爲'NSData',而將http://stackoverflow.com/a/25762128/1187415用於類似的方法。 - 轉換爲UTF-8 *不能*失敗。 –

+1

再次,我通過嘗試過快來犯一個基本錯誤:o謝謝,修正。 –

+0

不過,UTF-8可以表示所有Unicode字符串,所以我不認爲轉換可能會失敗。 –