Search code examples
c++encryptionblowfish

Is it the equivalent of doing CBC mode with a null iv?


If I initialize a IV with 8 null bytes. It makes block size equal to 8 (I think) and I could this code using CBC instead of ECB? Is that code equivalent of using CBC mode? Could we remove the loop if I use CBC? The key is 16 bytes long. I'm not encrypting the data, I receive it.

BF_KEY key = {{0}};
BF_set_key(&key, 16, key_data);

const int block_size = 8;
unsigned char previous[block_size] = {0}, decrypted[block_size] = {0};

for (auto it = replay_data.begin(); it != replay_data.end(); it += block_size) {
    BF_ecb_encrypt(reinterpret_cast<unsigned char*>(&(*it)), decrypted, &key, BF_DECRYPT);
    std::transform(previous, previous + block_size, decrypted, decrypted, std::bit_xor<unsigned char>());
    std::copy_n(decrypted, block_size, previous);
    std::copy_n(decrypted, block_size, reinterpret_cast<unsigned char*>(&(*it)));
}

Solution

  • CBC with a fixed IV is not equivalent to ECB.

    ECB processes each block in isolation:

    enter image description here

    On the other hand, CBC effectively uses each block of ciphertext as the next block's IV:

    enter image description here

    Assuming I'm reading the code correctly, your loop appears to be performing the XOR operation with the previous block's plaintext rather than its ciphertext, since you are copying from decrypted to previous after performing the decrypt and XOR step. I don't believe this corresponds to any well-known cipher mode, so I'm somewhat at a loss for an image here.