我正在尝试使用SHA-512算法从我的iOS应用程序复制Hmac生成行为,参考此链接Objective-C sample code for HMAC-SHA1。
为此,我尝试使用CrytoJS和jsSHA库来使用javascript代码计算Hmac。我发现这些javascript库生成的hmac值与我使用iOS代码的hmac值存在差异。
有人可以帮我理解我在这里做错了什么吗?我有一种感觉,我正在弄乱传递给这两种方法的键和计数器值的格式。
例如: key =“快速的棕色狐狸跳过懒狗” counter = 123
由iOS代码生成的Hmac- 8d4b0f7c7f800ffd656829b98988048b49b08d0068f6fd33add8a02b6bce8097cdd3a69dc8292ec7cc04e15021afb4499afe4a292f8db082b2d253ddfe7d7015
由javascript库生成的Hmac- 211935F67D87CBB6A98DE6A6D9D64F9AAF8DA5F09BF17F1B7E5BD46FCD9BEFBCD3585FB859BD042291AF5D79B6D92CF7B348CD6558A18AEF4328FAF344D63266
iOS代码:
NSData *key = [key dataUsingEncoding:NSASCIIStringEncoding];
NSData *rawKeyData = [DataUtil rawDataFromHex:key];
//encode the counter
uint8_t tosign[8];
for (int i = sizeof(tosign) - 1; i >= 0; i--) {
tosign[i] = counter & 0xff;
counter >>= 8;
}
unsigned char cHMAC[CC_SHA512_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA512, [rawKeyData bytes], [rawKeyData length], tosign, sizeof(tosign), cHMAC);
NSData *hmac = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
return hmac;
javascript代码:
var hash = CryptoJS.HmacSHA512("123", "The quick brown fox jumps over the lazy dog");
答案 0 :(得分:2)
HMAC获取数据键以及作为字节的键和数据参数,并返回由指定的散列函数确定的长度的字节。
示例:
+ (NSData *)doHmacSha512:(NSData *)dataIn
key:(NSData *)key
{
NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA512_DIGEST_LENGTH];
CCHmac( kCCHmacAlgSHA512,
key.bytes,
key.length,
dataIn.bytes,
dataIn.length,
macOut.mutableBytes);
return macOut;
}
测试:
NSData *keyData = [@"MyTestKey" dataUsingEncoding:NSASCIIStringEncoding];
NSData *data = [@"Now is the time for all good computers to come to the aid of their masters." dataUsingEncoding:NSASCIIStringEncoding];
NSData *hamcData = [Crypto doHmacSha512:data key:keyData]; // Where "Crypto" is the class "doHmacSha512" is defined in.