Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenSSL AES_cfb128_encrypt C++

I tried to implement a "very" simple encryption/decryption example. I need it for a project where I would like to encrypt some user information. I can't encrypt the whole database but only some fields in a table.

The database and most of the rest of the project works, except the encryption: Here is a simplified version of it:

#include <openssl/aes.h>
#include <openssl/evp.h>
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    /* ckey and ivec are the two 128-bits keys necessary to
       en- and recrypt your data.  Note that ckey can be
       192 or 256 bits as well
     */

    unsigned char ckey[] =  "helloworldkey";
    unsigned char ivec[] = "goodbyworldkey";

    int bytes_read;
    unsigned char indata[AES_BLOCK_SIZE];
    unsigned char outdata[AES_BLOCK_SIZE];
    unsigned char decryptdata[AES_BLOCK_SIZE];

    /* data structure that contains the key itself */
    AES_KEY keyEn;

    /* set the encryption key */
    AES_set_encrypt_key(ckey, 128, &keyEn);

    /* set where on the 128 bit encrypted block to begin encryption*/
    int num = 0;

    strcpy( (char*)indata , "Hello World" );
    bytes_read = sizeof(indata);

    AES_cfb128_encrypt(indata, outdata, bytes_read, &keyEn, ivec, &num, AES_ENCRYPT);
    cout << "original data:\t" << indata << endl;
    cout << "encrypted data:\t" << outdata << endl;

    AES_cfb128_encrypt(outdata, decryptdata, bytes_read, &keyEn, ivec, &num, AES_DECRYPT);
    cout << "input data was:\t" << decryptdata << endl;
    return 0;
}

But the output of "decrypted" data are some random characters, but they are the same after every execution of the code. outdata changes with every execution...

I tried to debug and search for a solution, but I couldn't find any solution for my problem.
Now my question, what is going wrong here? Or do I completely misunderstand the provided functions?

like image 499
user3059230 Avatar asked Feb 13 '23 01:02

user3059230


1 Answers

The problem is that AES_cfb128_encrypt modifies the ivec (it has to in order to allow for chaining). Your solution is to create a copy of the ivec and initialize it before each call to AES_cfb128_encrypt as follows:

const char ivecstr[AES_BLOCK_SIZE] = "goodbyworldkey\0";
unsigned char ivec[AES_BLOCK_SIZE];
memcpy( ivec , ivecstr, AES_BLOCK_SIZE);

Then repeat the memcpy before your second call to AES_cfb128_encrypt.

Note 1: Your initial vector was a byte too short, so I put an explicit additional \0 at the end of it. You should make sure all of your strings are of the correct length when copying or passing them.

Note 2: Any code which uses encryption should REALLY avoid using strcpy or any other copy of unchecked length. It's a hazard.

like image 108
Edward Avatar answered Feb 20 '23 07:02

Edward