使用密钥和消息在swift中创建哈希
问题描述:
我想在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?
答
的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)
答
Apple枚举值在Swift中有不同的定义。它可能定义为CCHmacAlgorithm.SHA1
而不是kCCHmacAlgSHA1
。
这是在这里找到答案: https://*.com/a/24411522/2708650
+1谢谢!你能帮我翻译其余的功能吗? – 2014-10-31 07:11:30
@artworkadシ:似乎只有十六进制字符串生成缺失,并在http://*.com/a/25762128/1187415中显示,我已经在上面的问题的答案中指出了这一点。 – 2014-10-31 07:41:33