How to perform unpadding after decryption of stream using CryptoPP

↘锁芯ラ 提交于 2019-12-08 08:00:08

问题


I've got the stream to decrypt. I divide it into blocks and pass each block to the method below. The data I need to decrypt is encrypted by 16 - bytes blocks and if the last block is less than 16, then all the rest bytes are filled by padding. Then in the moment of decryption I'm getting my last block result as the value including these additional padding bytes. How can I determine the length of original data and return only it or determine the padding bytes and remove them, considering different paddings could be used?

void SymmetricAlgorithm::Decrypt(byte* buffer, size_t dataBytesSize) {    
     MeterFilter meter(new ArraySink(buffer, dataBytesSize));
     CBC_Mode<CryptoPP::Rijndael>::Decryption dec(&Key.front(), Key.size(), &IV.front());
        StreamTransformationFilter* filter = new StreamTransformationFilter(dec, new Redirector(meter), PKCS_PADDING);
        ArraySource(buffer, dataBytesSize, true, filter);
        dec.Resynchronize(&IV.front());
}

Now I'm trying with PKCS_PADDING and Rijndael, but in general I might need work with any algorithm and any padding.


回答1:


I divide it into blocks and pass each block to the method below

In this case, you might consider calling ProcessBlock directly:

CBC_Mode<Rijndael>::Decryption dec(...);

// Assume 'b' is a 16-byte block
dec.ProcessBlock(b);

The block is processed in place, so its destructive. You will also be responsible for processing the last block, including the removal of padding.

By blocking and removing padding, you are doing the work of the StreamTransformationFilter (and friends).




回答2:


As it happens, I found what I needed occasionally in the example from this question. Appreciate your help, Gabriel L., but I didn't want make my method not to use padding at all. Sorry for unclear explanations, I wanted to extract plain data from decrypted data, which includes padding symbols. And the bold row in this code shows how to find out plain data bytes count.

void SymmetricAlgorithm::Decrypt(byte* buffer, size_t dataBytesSize) {    
 MeterFilter meter(new ArraySink(buffer, dataBytesSize));
 CBC_Mode<CryptoPP::Rijndael>::Decryption dec(&Key.front(), Key.size(), &IV.front());
    StreamTransformationFilter* filter = new StreamTransformationFilter(dec, new Redirector(meter), PKCS_PADDING);
    ArraySource(buffer, dataBytesSize, true, filter);
    int t = meter.GetTotalBytes(); //plain data bytes count
    dec.Resynchronize(&IV.front());
}


来源:https://stackoverflow.com/questions/19113633/how-to-perform-unpadding-after-decryption-of-stream-using-cryptopp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!