透明地解密数据的NSOutputStreamer的子类

时间:2017-05-03 20:37:05

标签: ios objective-c cocoa-touch encryption uikit

我有一个加密的数据流,我已经实现了一个或多或少类似于:

的功能
NSInteger DecryptContent(NSInputStream *inputStream,
                         NSOutputStream *outputStream,
                         NSData *key)
{
    NSInteger totalNumberOfWrittenBytes = 0;
    uint32_t recordSequenceNumber = 0;
    NSMutableData *ciphertextInput = [NSMutableData dataWithLength:recordSize];
    NSData *plaintextOutput = nil;
    NSInteger recordDelimiterIndex = -1;
    do {
        CodingHeader *codingHeader = ReadCodingHeaderFromInoutStream(inputStream);
        NSInteger numberOfReadBytes = [inputStream read:ciphertextInput.mutableBytes maxLength:codingHeader.recordSize];
        if (numberOfReadBytes <= 0) {
            LogError(@"Error: Stream should not have ended");
            return -1;
        }
        NSData *actualCiphertextInput = ciphertextInput;
        // Last chunk
        if (numberOfReadBytes != ciphertextInput.length) {
            actualCiphertextInput = [ciphertextInput subdataWithRange:NSMakeRange(0, numberOfReadBytes)];
        }

        NSData *scrambledKey = ScrambleKeyWithRecordSequenceNumberAndSalt(recordSequenceNumber, codingHeader.salt);
        plaintextOutput = Decrypt(actualCiphertextInput, scrambledKey);

        recordDelimiterIndex = FindRecordDelimiterIndex(plaintextOutput);
        if (recordDelimiterIndex < 0) {
            LogError(@"Error: Delimiter not found");
            return -2;
        }

        NSInteger numberOfWrittenBytes = [outputStream write:plaintextOutput.bytes maxLength:recordDelimiterIndex];
        if (numberOfWrittenBytes == -1) {
            LogError(@"Error writing bytes: %@", outputStream.streamError);
            return -3;
        }
        totalNumberOfWrittenBytes += numberOfWrittenBytes;
        recordSequenceNumber++;
    }  while (((uint8_t *)plaintextOutput.bytes)[recordDelimiterIndex] != LastRecordDelimiterByte);
    return totalNumberOfWrittenBytes;
}

这不是理想的,因为它是一个在流上使用轮询的阻塞函数。将此代码调整为NSOutputStream子类,以便在运行时透明地解密数据的好方法是什么?还有其他任何异步的选择吗?

我是否必须覆盖- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)length并使用我自己的中间缓冲区管理解密,还是有更好/更简单的方法?

如果我必须管理自己的缓冲区,无法使用NSInputStream方便地读取数据(并且必须使用缓冲区偏移,将多个读取连接到一个加密记录等) 。)似乎是一个巨大的痛苦。

0 个答案:

没有答案