AES-256 example code encrypting multiple subsections of plaintext with the same initialization vector I have been dabbling a bit into encryption in C++ using Brian Gladman's implementation found here:

https://github.com/BrianGladman/AES

I also found some example code that uses this library found here:

http://forums.devshed.com/programming-42/aes-encrypt-decrypt-687368.html

The relevant bits of code are as follows:

void encrypt(const char *fileIn, const char *fileOut, 
    const unsigned char *key) {
    ...
    /* pick a random initialisation vector */
    for(i = 0; i &lt; 16; ++i)
        iv[i] = rand() &amp; 0xFF;
    fwrite(iv, 1, 16, outFile);

    aes_encrypt_key256(key, ctx);
    while((i = fread(inBuffer, 1, sizeof(inBuffer), inFile)) &gt; 0) {
        aes_ofb_crypt(inBuffer, outBuffer, i, iv, ctx);
        fwrite(outBuffer, 1, i, outFile);
    }
    ...
}




void decrypt(const char *fileIn, const char *fileOut, 
const unsigned char *key) {
    ...
    /* read initialization vector from file */
    if(fread(iv, 1, 16, inFile) &lt; 16) {
        ...
        return; /* error: file doesn't even contain an initialisation vector */
    }

    aes_encrypt_key256(key, ctx);
    while((i = fread(inBuffer, 1, sizeof(inBuffer), inFile)) &gt; 0) {
        aes_ofb_crypt(inBuffer, outBuffer, i, iv, ctx);
        fwrite(outBuffer, 1, i, outFile);
    }
    ...
}


However, after reading through the last answer on:

Why is AES resistant to known-plaintext attacks?

It seems like that chunking the input text and encrypting each chunk using the same initialization vector is a bad idea.  I just wanted to ask if this implementation is flawed from a security perspective or is there a valid reason for encrypting each chunk of text with the same initialization vector? 

In addition, are there compelling reasons for chunking the plaintext in this way to begin with (where each chunk has its own initialization vector, that is)?

Thanks in advance for any responses.
It seems like that chunking the input text and encrypting each chunk using the same initialization vector is a bad idea


You are quite right to be concerned. It wouldn't only be a bad idea; it would be an absolutely dreadful one.  With OFB mode, reusing an IV would cause the same bitpattern to be exclusive-or'ed with the plaintext to form the ciphertext; hence if the attacker takes the two ciphertexts with the same IV and exclusive-or's them, they'll get the two plaintexts exclusive-or'ed together.  From that, it is often not that difficult to recover the original plaintexts (as real plaintexts often have enough redundancy to allow this).

However, that's not what's happening here.

As a part of its processing, aes_ofb_crypt updates the IV it was passed; hence calling it multiple times will cause it to use a different IV each time.  Hence, this problem is avoided (and so this code is safe).