Search code examples
windowsvisual-c++aesencryption-symmetriccryptoapi

How to encrypt a file using Crypto API with multiple threads?


I am trying to encrypt a file using multiple threads and Crypto API / AES256 / CBC mode / NO IV (initialization vector) is used.

I am dividing the file into as many number of threads. The thread which gets the last block of the file, does a CryptEncrypt passing Final as true.

Following the approach suggested here: Each thread uses a duplicated key.

Additionally, each thread opens the source file in shared read mode and starts reading from the offset allotted, keeping encrypting and writing to the destination file (again opened in shared write mode) as appropriate offsets.

The output file which i get in case of single and multi threaded is not the same and hash mismatches. What is that i am doing wrong?


Solution

  • You cannot do that. IV or chaining mode is irrelevant here (though some chaining mode allows parallelism - but is would be its implementation). Consider performing encryption of following text:

    "Block cipher mode of operation"
    

    Somehow you divide it this way (2 threads):

    • "Block cipher mo"
    • " de of operation"

    How can you be sure that it gets executed (by OS scheduler) in the same sequence? If you divide it into 3 threads, it may be:

    • "Block ciphe"
    • "r mode o"
    • "f operation"

    but it may get executed as:

    • "r mode o"
    • "f operation"
    • "Block ciphe"

    The end result, as you can guess, would be different!

    Also, with CBC mode, the result depends on previous outcome, a mentioned here. See, on the right side, CBC is not parallelizable.