2

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","pubKey":"75948458","sig":"val"}

4

1 回答 1

1

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

如果您仍然希望尽可能多地查看字符串,您可以这样做。

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

而且我在下面的行中也取得了一些成功。(打印与上面不同的字符串)

NSLog(@"encrypted data: %@", [[[NSString alloc] initWithData:output encoding:NSISOLatin2StringEncoding] autorelease]);
于 2011-06-22T18:38:00.573 回答