问题
I am trying to replicate the Hmac generation behavior from my iOS app using SHA-512 algorithm referring to this link Objective-C sample code for HMAC-SHA1.
For this purpose, I have tried using CrytoJS and jsSHA libraries to compute the Hmac using javascript code. I have found discrepancies in hmac values generated by these javascript libraries and the one that I have using my iOS code.
Can someone help me understand what could I be doing wrong here? I have a feeling that I am messing up with the format of key and counter values that are being passed to both the methods.
For example: key = "The quick brown fox jumps over the lazy dog" counter = 123
Hmac generated by iOS code- 8d4b0f7c7f800ffd656829b98988048b49b08d0068f6fd33add8a02b6bce8097cdd3a69dc8292ec7cc04e15021afb4499afe4a292f8db082b2d253ddfe7d7015
Hmac generated by javascript libraries- 211935F67D87CBB6A98DE6A6D9D64F9AAF8DA5F09BF17F1B7E5BD46FCD9BEFBCD3585FB859BD042291AF5D79B6D92CF7B348CD6558A18AEF4328FAF344D63266
iOS Code:
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 Code:
var hash = CryptoJS.HmacSHA512("123", "The quick brown fox jumps over the lazy dog");
回答1:
HMAC takes a data key and a key and data parameters which are bytes and returns bytes of a length determined by the hash function specified.
Example:
+ (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;
}
Test:
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.
来源:https://stackoverflow.com/questions/30387437/hmac-sha-512-generation-discrepancies-between-ios-and-javascript-libraries