我想在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謝謝!你能幫我翻譯其餘的功能嗎? – 2014-10-31 07:11:30
@artworkadシ:似乎只有十六進制字符串生成缺失,並在http://stackoverflow.com/a/25762128/1187415中顯示,我已經在上面的問題的答案中指出了這一點。 – 2014-10-31 07:41:33