Search code examples
c++cng

C++ - Decrypting without encryption size


I've looked for a while and I have not found the solution to this problem. I am using BCryptDecrypt to decrypt my encrypted data but it requires the size of the EncryptedData, How are you able to decrypt without knowing the size?

I know BCryptEncrypt gives you the length after it has successfully encrypted the data, the only way I know how I would be able to is send it with the encrypted data / IV.

For example: Let's say I were to encrypt data and then send it over a socket with the IV to my WinSock server that would decrypt the data. How would that server be able to decrypt it without knowing the size? even though it knows the Key and IV.

Thanks


Solution

  • If size is required, I see two ways to get it:

    • Send it explicitly together with the encrypted data.
    • Buffer all data on server side until it is received completely. Keep track of how many bytes you received.

    With first, you could try something like this:

    <number of bytes to follow><separator symbol><message data>
    

    Second requires that you are able to detect the end of the message properly. You could detect this via a specific message end sequences. Then, however, you need to escape such a sequence within the message, if it appears. Something similar to how characters are escaped in C/C++/Java/C#... If not chosing the first approach, which appears the simplest to me, this is what I would probably prefer against the variant below...

    An alternative might be closing the connection after a message is complete. Then, however, you need to detect if the connection was closed regularly or if it got broken, because in the latter case, you must not try to decode...

    You might even combine both approaches:

    <message start sequence>
    <number of bytes to follow>
    <separator symbol>
    <encrypted data>
    <message end sequence>
    

    Both message start sequence and message end sequence would have to be escaped. If you detect message start sequence then within the encrypted data, or message end sequence before number of bytes have been read, you know on server side, that something has gone badly wrong...