Вопрос

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.

Это было полезно?

Решение 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());
}

Другие советы

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).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top