I wrote a small code to compute the time consumption by the AES in CBC mode, I noticed that the encryption is faster than the decryption, my question: Is my result correct? If yes, why is the encryption faster?
I notice that AES-CBC encryption is faster than the description, is my result is correct?
It is plausible for a software-only implementation if single-threaded or if CPU time is cumulated across the multiple threads. For an implementation using AES instructions, the difference in speed can be barely noticeable or in either direction. For a competently made multi-threaded implementation with concurrently running threads and speed measured according to wall clock time elapsed, decryption of large amounts of data should be much faster than encryption.
- AES CBC decryption involves the AES block cipher in decryption mode (when AES CTR does not), and in AES (contrary to DES) the design of the block cipher has reasons to make it slower in decryption mode:
- The MixColumns step of encryption purposely uses a matrix with many coefficients at 1, when the inverse MixColumns used in decryption does not, thus requires more field operations. However that often makes no speed difference in hardware-assisted implementations.
- The derivation of the AES round subkeys from the main key can be performed as the rounds are applied in encryption mode, but not in decryption mode, where the first subkey used is the last derived one. However that will make no difference for implementations that compute round subkeys only once, which is typical of software implementations optimized for many blocks.
- Implementations of decryption that both decipher in place and process data blocks in the order used in encryption (rather than reverse) need to keep a copy of the previous ciphertext block in order to decipher the next, and that can add some time.
- Sometime decryption is just not optimized as carefully as encryption is.
Among reasons why AES CBC decryption can be faster:
- Decryption can be trivially parallelized on multiple CPUs, when encryption cannot (because the output of the previous block encryption needs to be known to prepare the input of the next block encryption). That leads to less wall clock time for decryption of multiple blocks in multi-threaded implementations when multiple CPUs or even simultaneous multithreading is available.
- For the same reason, on architectures with high instruction latency, a single thread can interleave the decryption of multiple blocks from the same encrypted data stream and reach higher performance than for encryption (BearSSL uses that, as noted by SEJPM).
- Decryption does not need to generate a random IV, when encryption does.