0

I have used the following code to encrypt and decrypt an XML file:

int bytes_read, bytes_written;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char ckey[] = "thiskeyisverybad";
unsigned char ivec[] = "dontusethisinput";

AES_KEY key;

AES_set_encrypt_key(ckey, 128, &key);

int num = 0;
FILE * ifp = fopen("Test.XML","rb");
FILE * ofp = fopen("Enc.XML", "wb");
while (1) {
    bytes_read = fread(indata, 1, AES_BLOCK_SIZE, ifp);

    AES_cfb128_encrypt(indata, outdata, bytes_read, &key, ivec,&num,AES_ENCRYPT);

    bytes_written = fwrite(outdata, 1, bytes_read, ofp);
    if (bytes_read < AES_BLOCK_SIZE)
        break;
}

num = 0;
FILE * ifpe = fopen("Enc.XML", "wb");
FILE * ofpe = fopen("TestDec.XML", "rb");

while (1) {
    bytes_read = fread(indata, 1, AES_BLOCK_SIZE, ifpe);
    AES_cfb128_encrypt(indata, outdata, bytes_read, &key, ivec, &num, AES_DECRYPT);

    bytes_written = fwrite(outdata, 1, bytes_read, ofpe);
    if (bytes_read < AES_BLOCK_SIZE)
        break;
}

I have referred to the link Encrypting and decrypting a small file using openssl. I am getting an encrypted file in Enc.XML. When I try the decrypt code, a file is getting created by blank records. Wanted to know what is missed in decrypt code.

Programmer
  • 329
  • 2
  • 6
  • 25
  • Can I know the reason for down vote? I have already found the reply in stack overflow itself, but decrypt logic is not working. – Programmer Jan 10 '19 at 17:28
  • What is your cleartext? (That is, what is in `Text.XML`?) – Beta Jan 10 '19 at 17:49
  • The content doesnt matter right, it is an XML file. The below answer has solved my query. Wondering why the question is down voted. – Programmer Jan 18 '19 at 06:11

1 Answers1

1

The "ivec" buffer in modified with each call to AES_cfb128_encrypt. If your code is not two programs but one problem, like what you have above, then you need to reset the "ivec" buffer back to the original value before attempting the decryption.

Something like:

char ivec[16];
…
memcpy(ivec, "dontusethisinput", 16);
… encrypt code
memcpy(ivec, "dontusethisinput", 16);
… decrypt code
Shane Powell
  • 13,698
  • 2
  • 49
  • 61