I am trying to code AES using Cipher Block Chaining(CBC) mode. I am pretty sure that I have the structure correct (xoring the previous ciphertext with the new plaintext before sending it to AES and the reverse when I decrypt. The problem I am having is with decrypting the encrypted file back to the original plaintext. I think it might have something to do with the way that it is xored. I know that my AES algorithm is correct. I xor two character arrays together. I know that if you take the results of xoring two things together and then xor one of them back with the answer, you should get the other operand back. However, when I check that functionality, it does not work like that.
Where I read it in the plaintext and xor it with the previous ciphertext
//THERE IS A RANDOM INITIALIZATION VECTOR BEFORE GETTING INTO THE WHILE LOOP
while ((bytes_in = (read(fin, plaintext, AES_BLOCK)) ))
{
for (count = 0; count < AES_BLOCK; count++){
xor[count] = (plaintext[count]) ^ (ciphertext[count]);
}
//AES STUFF NOT SHOWN SO THERE ISN'T MUCH CODE
status = write (fdsk, ciphertext, strlen (ciphertext));
for (count =0; count < AES_BLOCK; count++)
plaintext[count] = '0';
}
The decrypting part:
bytes = read(fin, previous_CT, AES_BLOCK); //reads in the initialization vector
while(total_bytes < aes_length)
{
bytes = read(fin, ciphertext, AES_BLOCK);
for(count = 0; count < AES_BLOCK; count++){
plaintext[count] = (xor[count]) ^ (previous_CT[count]);
printf("plaintext %d", plaintext[count]);
}
}
To sum up my problem/question:
I’m wondering if there is something to xoring characters that I am not aware I need to do. It seems like I am doing it the correct way but for some reason I am not getting the correct results. I am also wondering if it could be the way I am reading the information in that is messing up my program. Please help me out!
Thanks!
The bug that jumps out at me is on this line:
I’m pretty sure you really want:
Both versions may produce the same results much of the time, but occasionally a cipher produces the byte ‘\0’ somewhere in the middle of the ciphertext, and then the first buggy version truncates the write to something shorter than you wanted.
(The same problem occurs in XORing "Hello World!" cuts off string ).
I get all 0’s from the xor operation
That only happens when you have exactly the same values on the left and right side of the XOR operation.
Are you maybe accidentally copying data into the wrong buffer, or prematurely copying data for later use, ending up with a duplicate copy of data on the left and right side?