使用CommonCrypto / CommonHMAC加密一些数据,并始终返回null [英] Using CommonCrypto/CommonHMAC to encrypt some data and always comes back null

查看:146
本文介绍了使用CommonCrypto / CommonHMAC加密一些数据,并始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用密钥 keyData 加密 clearTextData 。我确实检查了这两个值是否有效并经过。

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]]);

日志总是回来说加密数据:(null)

任何想法?

*更新*

以下是我传递的关键字和数据的示例:

Here are examples of the key and data that I am passing:


键:983745hjhgfd3454

key: 983745hjhgfd3454

data:
{data:lala,pubKey:75948458,sig:val}

data: {"data":"lala","pubKey":"75948458","sig":"val"}


推荐答案

来自加密的此数据是数据,并尝试将其转换为字符串编码失败。您正在指定UTF8编码,我也尝试过UTF32编码,并且失败。只需记录返回的数据,因为这些十六进制值比字符串表示更有利。

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]);

这篇关于使用CommonCrypto / CommonHMAC加密一些数据,并始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆