Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

iphone - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...