我正在使用 AES 256 进行加密解密,我有大约 1 - 2 GB 的较大文件,它应该通过 Encryption and Decryption Process ,在对下载的文件进行加密时,我收到内存警告和应用程序崩溃。所以我想知道如何逐块进行加密解密以减少内存使用量。
以下是我正在使用的代码片段:-
- (NSData *)AES256EncryptWithKey:(NSString *)key
{
char keyPtr[kCCKeySizeAES256 + 1];
bzero( keyPtr, sizeof( keyPtr ) );
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL ,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted );
if( cryptStatus == kCCSuccess )
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free( buffer );
return nil;
}
- (NSData *)AES256DecryptWithKey:(NSString *)key
{
char keyPtr[kCCKeySizeAES256+1];
bzero( keyPtr, sizeof( keyPtr ) );
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL ,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted );
if( cryptStatus == kCCSuccess )
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free( buffer );
return nil;
}
谢谢你,罗希特·扬卡尔