如何使用CCCrypt()加密文件?

时间:2011-04-06 10:08:08

标签: iphone objective-c ios ipad

当我加密文件(doc,pdf等)时,我使用:

size_t bufferSize = dataLength + kCCBlockSizeAES128;    
CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                 keyPtr, kCCKeySizeAES256,
                                 NULL /* initialization vector (optional) */,
                                 dataBytes, dataLength, /* input */
                                 buffer, bufferSize,/* output */
                                 &numBytesEncrypted );

解密时,我使用:

size_t bufferSize = dataLength + kCCBlockSizeAES128;
CCCryptorStatus result = CCCrypt( kCCDecrypt, kCCAlgorithmAES128,    kCCOptionPKCS7Padding,
                                 keyPtr, kCCKeySizeAES256,
                                 NULL /* initialization vector (optional) */,
                                 dataBytes, dataLength,/* input */
                                 buffer, bufferSize,/* output */
                                 &numBytesEncrypted );

但是当解密时,它会返回错误:kCCDecodeError = -4304。

如果我在解密时删除了kCCOptionPKCS7Padding的参数,则没有错误。但该文件也无法打开。

那么,你能告诉我如何通过这些参数吗?

非常感谢!

3 个答案:

答案 0 :(得分:4)

这用于加密

    NSString *key =@"YourKey";
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero( keyPtr, sizeof(keyPtr) ); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char *dataIn = "This is your data";
    char dataOut[500];// set it acc ur data
    bzero(dataOut, sizeof(dataOut));
    size_t numBytesEncrypted = 0;

    CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding,  keyPtr,kCCKeySizeAES256, NULL, dataIn, strlen(dataIn), dataOut, sizeof(dataOut), &numBytesEncrypted);

这是用于解密

char dataOut2[500];
bzero(dataOut2, sizeof(dataOut2));
size_t numBytesDecrypted = 0;   

CCCryptorStatus result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding, keyPtr,kCCKeySizeAES256, NULL, dataOut, numBytesEncrypted, dataOut2, sizeof(dataOut2), &numBytesDecrypted);

答案 1 :(得分:1)

更改行

bzero(dataOut, sizeof(dataOut2));

bzero(dataOut2, sizeof(dataOut2));

谢谢Inder

答案 2 :(得分:0)

好的,我知道了!还成功测试了它。该行应该是:

CCCrypt(kCCDecrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding, keyPtr,kCCKeySizeAES256, NULL, dataOut, numBytesEncrypted, dataOut2, sizeof(dataOut2), &numBytesDecrypted);