Using CommonCrypto/CommonHMAC to encrypt some data and always comes back null
I tried the following to encrypt the clearTextData
using the key keyData
. And I did check to make sure that both of those values are valid and going through.
NSData *keyData = [PRIVATE_KEY dataUsingEncoding:NSUTF8StringEncoding];
NSData *clearTextData = [data dataUsingEncoding:NSUTF8StringEncoding];
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
CCHmacContext hmacContext;
CCHmacInit(&hmacContext, kCCHmacAlgSHA1, keyData.bytes, keyData.length);
CCHmacUpdate(&hmacContext, clearTextData.bytes, clearTextData.length);
CCHmacFinal(&hmacContext, digest);
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
NSLog(@"encrypted data: %@", [NSString stringWithUTF8String:[out bytes]]);
The log always comes back saying encrypted data: (null)
Any ideas?
* UPDATE *
Here are examples of the key and data that I am passing:
key: 983745hjhgfd3454
data: {"data":"lala","pu开发者_StackOverflow中文版bKey":"75948458","sig":"val"}
This data from the crypto is data and attempting to turn it into string is failing on the encoding. You are specifying UTF8 encoding and I have also tried UTF32 encoding and that fails as well. Just log the data returned as those hex values are more beneficial than a string representation.
If you would still like to see as much as the string as possible you can do this.
NSData *output = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
//This is useful
NSLog(@"encrypted data: %@", output);
//Not useful but you may be able to visualize some of the string
char *outstr = malloc(sizeof(char) * (CC_SHA1_DIGEST_LENGTH + 1));
memcpy(outstr, [output bytes], CC_SHA1_DIGEST_LENGTH);
outstr[CC_SHA1_DIGEST_LENGTH] = 0;
NSLog(@"encrypted data string: %s", outstr);
free(outstr);
And I also had some success with the following line.(Prints a different string than above)
NSLog(@"encrypted data: %@", [[[NSString alloc] initWithData:output encoding:NSISOLatin2StringEncoding] autorelease]);
精彩评论