最近,我正在使用CCCrypt来实现一些自定义的加密算法。但是,当我使用CCCryptorUpdate解密密文时,输出始终比原始纯文本少8个字节。以下是我的代码:
+ (void) EncryptBy3DES:(NSInputStream*)strmSrc Output:(NSOutputStream*)strmDest CryptoRef:(CCCryptorRef)tdesCrypto
{
size_t dataOutMoved;
uint8_t inputBuf[BlockSize];
uint8_t outputBuf[BlockSize];
CCCryptorStatus cryptStatus;
int iBytesRead = 0;
while ( (iBytesRead = [strmSrc read:inputBuf maxLength:BlockSize]) > 0 )
{
NSLog(@"Bytes read from plain buffer: %d", iBytesRead);
[Util FillBuffer:inputBuf Length:BlockSize Current:iBytesRead];
cryptStatus = CCCryptorUpdate(tdesCrypto, &inputBuf, BlockSize, &outputBuf, BlockSize, &dataOutMoved);
assert(dataOutMoved<=BlockSize && cryptStatus==noErr);
NSLog(@"EncDataOutMoved: %ld", dataOutMoved);
[Util FillBuffer:outputBuf Length:BlockSize Current:dataOutMoved];
[strmDest write:outputBuf maxLength:BlockSize];
}
}
+ (void) DecryptBy3DES:(NSInputStream*)strmSrc Output:(NSOutputStream*)strmDest CryptoRef:(CCCryptorRef)tdesCrypto
{
size_t dataOutMoved;
uint8_t inputBuf[BlockSize];
uint8_t outputBuf[BlockSize+kCCBlockSize3DES];
CCCryptorStatus cryptStatus;
int iBytesRead = 0;
while ( (iBytesRead = [strmSrc read:inputBuf maxLength:BlockSize]) > 0 )
{
NSLog(@"Bytes read from cipher buffer: %d", iBytesRead);
cryptStatus = CCCryptorUpdate(tdesCrypto, &inputBuf, BlockSize, &outputBuf, BlockSize+kCCBlockSize3DES, &dataOutMoved);
NSLog(@"Lengh needed: %zu", CCCryptorGetOutputLength(tdesCrypto, BlockSize, YES));
NSLog(@"DecDataOutMoved: %ld", dataOutMoved);
assert(dataOutMoved<=BlockSize && cryptStatus==noErr);
[strmDest write:outputBuf maxLength:dataOutMoved];
}
}
I encrypted 3 buffer of 4096. When decrypting them, the log shows that the size of 1st decrypted data is 4088, BUT! The missing data is actually in the begining of the 2nd decrypted data.
2012-04-14 15:17:41.929 otest[25168:7803] Bytes read from cipher buffer: 4096
2012-04-14 15:17:41.929 otest[25168:7803] Lengh needed: 4104
2012-04-14 15:17:41.930 otest[25168:7803] DecDataOutMoved: 4088
end of 1st block:<..d71eaf27 affc4c8c b1c54afa c5434397 ebc17a49>
2012-04-14 15:17:45.291 otest[25168:7803] Bytes read from cipher buffer: 4096
2012-04-14 15:17:45.292 otest[25168:7803] Lengh needed: 4104
2012-04-14 15:17:45.293 otest[25168:7803] DecDataOutMoved: 4096
begining of 2nd block <**86b61bce b4342728** 88240a64 837327d4 0bb572a2 f5220928
请注意, 86b61bce b4342728 在加密之前的第一个块的末尾。
我还检查了第一个程序段的开头,并且确定不会弄乱数据范围。看来数据已解密,但是直到下一个操作才检索它们。
我想在每个加密/解密操作中获得完整的块,但是我不想使用CCCrypt函数,因为我必须将Key和Iv位都传递给它。我只想将CCCryptorRef传递给它,这相对简单。
休伯特
最佳答案
您需要通过调用 CCCryptFinal
完成加密和解密。这将负责添加/删除填充。
关于objective-c - CCCrypt解码的明文长度错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10152042/