我正在使用 RNCryptor 加密文件,对于大文件,我使用 NSInputStream 将文件分成块并编码/解码这些块。在我需要对传递给流的块进行 base64 编码/解码之前,它工作得很好。
以下代码非常适合编码,除了它不进行 base64 编码:
NSInputStream *tmpStream = [[NSInputStream alloc] initWithURL:fileURL];
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[tmpStream open];
[outputStream open];
__block NSMutableData *data = [NSMutableData dataWithLength:kBlockSize];
__block RNEncryptor *encryptor = nil;
dispatch_block_t readStreamBlock = ^{
[data setLength:kBlockSize];
NSInteger bytesRead = [tmpStream read:[data mutableBytes] maxLength:kBlockSize];
if (bytesRead < 0) {
NSLog(@"An error occurred while decrypting file stream");
if (resultBlock) { resultBlock(nil); }
return;
}
else if (bytesRead == 0){
[encryptor finish];
}
else {
[data setLength:bytesRead];
[encryptor addData:data];
}
};
encryptor = [[RNEncryptor alloc] initWithSettings:kRNCryptorAES256Settings
password:HUCryptorPassword
handler:^(RNCryptor *cryptor, NSData *data) {
[outputStream write:data.bytes maxLength:data.length];
if(cryptor.isFinished){
[outputStream close];
if (resultBlock) {
resultBlock([NSString stringWithFormat:@"%@", filePath]);
}
}
else {
readStreamBlock();
}
}];
readStreamBlock();
我尝试在数据加密后和写入输出流之前添加 base64 编码:
NSData *base64Data = [data base64EncodedDataWithOptions:kNilOptions]; //Tried with all options
[outputStream write:base64Data.bytes maxLength:base64Data.length];
但这在输出文件中给了我不正确的结果。
我获得正确编码/解码数据的唯一正确方法是将整个文件加载到内存中并调用编码/解码方法。
NSData *resultData = [NSData dataWithContentsOfFile:filePath]; //This is location of output file stream
NSData *encodedData = [resultData base64EncodedDataWithOptions:kNilOptions]; //Gives me correct base64 encoded data
我想避免这种情况,因为我需要对大文件进行编码/解码,例如视频、声音和图像。
有什么安全的方法可以做到这一点吗?