Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CCCrypt() to encrypt a file?

when I encrypt a 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 decrypt, 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 decrypt, it returns error:kCCDecodeError = -4304.

If I remove the param of kCCOptionPKCS7Padding when decrypt, there is no error. But the file cannot open either.

So, could u tell me how to pass these params?

thanks alot!

like image 314
EVA Avatar asked Apr 06 '11 10:04

EVA


People also ask

How do I encrypt a file in shell script?

You can save a key to a file by running ./encrypt.sh -g > encryption. key . To encrypt a file use the -e option and specify the {input-file} (file to encrypt) and {output-file} (encrypted file). You can use a -k Key, -p Password, or leave the parameter blank in order to be prompted for a password.


2 Answers

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

this 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);
like image 67
Inder Kumar Rathore Avatar answered Sep 28 '22 05:09

Inder Kumar Rathore


Change the line

bzero(dataOut, sizeof(dataOut2));

to

bzero(dataOut2, sizeof(dataOut2));

Thanks Inder

like image 22
Abhilash Divakaran Avatar answered Sep 28 '22 04:09

Abhilash Divakaran