Programmer
Programmer

Reputation: 439

Open SSL simple encrypt / decrypt C++

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.

Upvotes: 0

Views: 1625

Answers (1)

Shane Powell
Shane Powell

Reputation: 14138

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

Upvotes: 1

Related Questions