How to use CCCrypt () to encrypt a file?

when I encrypt the file (doc, pdf, etc.) I use:

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

when decrypting, I use:

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

But when decrypting, it returns an error: kCCDecodeError = -4304.

If I remove the kCCOptionPKCS7Padding parameter during decryption, no error occurs. But the file also does not open.

So, could you tell me how to pass these parameters?

Thank you so much!

+5
source share
3 answers

This is for encryption

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

it is for decryption

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);
+4
source

Change the line

bzero(dataOut, sizeof(dataOut2));

to

bzero(dataOut2, sizeof(dataOut2));

Thanks Inder

+1
source

, ! . :

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

All Articles