使用密钥和消息在swift中创建哈希 [英] Create hash in swift using key and message
问题描述
我想使用swift中的键创建字符串的SHA1 hmac哈希。在obj-c中我使用了它并且效果很好:
I want to create an SHA1 hmac hash of a string using a key in swift. In obj-c I used this and it worked great:
+(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。这是我到目前为止:
However now I am having a hard time to translate this into swift. This is what I have so far:
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?
already gives me an error Int is not convertible to CCHmacAlgorithm. Any ideas how to translate the obj-c code to swift?
推荐答案
CCHmac的最后一个参数()
函数的类型为 UnsafeMutablePointer< Void>
,因为
就是写入的结果。您必须将 cHMAC
声明为变量
并将其作为输入输出表达式传递给&安培;
。此外,某些类型的转换
是必要的:
The last parameter of the CCHmac()
function has the type UnsafeMutablePointer<Void>
because
that's where the result is written to. You have to declare cHMAC
as variable
and pass it as an in-out expression with &
. In addition, some type conversions
are necessary:
var cHMAC = [CUnsignedChar](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey, UInt(cKey.count), cData, UInt(cData.count), &cHMAC)
这篇关于使用密钥和消息在swift中创建哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!