这是我的代码:
-(IBAction)encryptText:(id)sender
{
key = self.tvKey.text;
CCCryptorStatus status = kCCSuccess;
algorithm = kCCAlgorithmAES128;
CCOptions opts = kCCOptionPKCS7Padding;
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSString *plainString = [NSString stringWithFormat:@"%@", self.tvEntryText.text];
NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [plainData dataEncryptedUsingAlgorithm: algorithm
key: keyData
initializationVector: nil
options: opts
error: &status];
if ( status != kCCSuccess ) {
NSError * err = [NSError errorWithCCCryptorStatus: status];
self.lblKeyMsg.text = [NSString stringWithFormat:@"Encryption failed: %s", [[err localizedDescription] UTF8String]];
self.lblKeyMsg.textColor = [UIColor redColor];
return;
}
NSString *encryptedString = [[[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding] autorelease];
self.tvResultText.text = encryptedString;
}
倒数第二个语句我将加密的 NSData 转换为 NSString 用于显示目的,但它返回 nil。Nil 是指示和错误的有效响应。我在该语句运行后立即停止了执行,这里是 vaues:
(gdb) po keyData
<61616161 61616161 61617373 73737373 73737373 64646464 64646464 64646666>
(gdb) po key
aaaaaaaaaassssssssssddddddddddff
(gdb) po plainString
this is a test.
(gdb) po plainData
<74686973 20697320 61207465 73742e>
(gdb) po encryptedData
<f7074146 b295e340 0d947d53 9ea629cf>
(gdb) po encryptedString
Can't print the description of a NIL object.
(gdb) po status
Can't print the description of a NIL object.
(gdb)
状态为 nil 表示加密中没有错误。所有值似乎都符合预期,但 initWithData 失败。下面是操作 iPhone 视图:
为什么 initWithData 在这里失败?