2014-10-30 62 views
0

我想在swift中使用一個鍵創建一個字符串的SHA1 hmac哈希。在obj-c我用這個,它工作得很好:使用密鑰和消息在swift中創建哈希

+(NSString *)sha1FromMessage:(NSString *)message{ 

    const char *cKey = [API_KEY cStringUsingEncoding:NSASCIIStringEncoding]; 
    const char *cData = [message cStringUsingEncoding:NSUTF8StringEncoding]; 

    NSLog(@"%s", cData); 

    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH]; 

    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC); 
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)]; 

    const unsigned char *buffer = (const unsigned char *)[HMACData bytes]; 
    NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2]; 

    for (int i = 0; i < HMACData.length; ++i){ 
     [HMAC appendFormat:@"%02hhx", buffer[i]]; 
    } 
    return HMAC; 
} 

但是現在我很難將其翻譯成swift。這是我到目前爲止有:

static func sha1FromMessage(message: String){ 

     let cKey = RestUtils.apiKey.cStringUsingEncoding(NSASCIIStringEncoding)! 
     let cData = message.cStringUsingEncoding(NSUTF8StringEncoding)! 
     let cHMAC = [CUnsignedChar](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) 

     CCHmac(kCCHmacAlgSHA1, cKey, cKey.count, cData, cData.count, cHMAC) 
     ... 
} 

這行

CCHmac(kCCHmacAlgSHA1, cKey, cKey.count, cData, cData.count, cHMAC) 

已經給我一個錯誤int是無法轉換爲CCHmacAlgorithm。任何想法如何將obj-c代碼轉換爲swift?

回答

1

CCHmac()函數的最後一個參數的類型爲UnsafeMutablePointer<Void>,因爲 這就是結果是寫入。您必須聲明cHMAC變量 並將其作爲輸入輸出表達式&傳遞。另外,一些類型轉換 是必要的:

var cHMAC = [CUnsignedChar](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) 
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey, UInt(cKey.count), cData, UInt(cData.count), &cHMAC) 
+0

+1謝謝!你能幫我翻譯其餘的功能嗎? – 2014-10-31 07:11:30

+0

@artworkadシ:似乎只有十六進制字符串生成缺失,並在http://stackoverflow.com/a/25762128/1187415中顯示,我已經在上面的問題的答案中指出了這一點。 – 2014-10-31 07:41:33