Encryption and Decryption using C++

Dani Marian Morar picture Dani Marian Morar · Jan 30, 2014 · Viewed 18k times · Source

I've got a buffer, in which i'm adding some plain text. I want to use openssl AES encryption to encrypt the text, then decrypt it, and print it back on the screen.

Code is running with no errors.

#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string>
#include <openssl/aes.h>
using namespace std;

void main()
{

// Buffers
unsigned char inbuffer[1024];
unsigned char encryptedbuffer[1024];
unsigned char outbuffer[1024];


// CODE FOR ENCRYPTION
//--------------------
unsigned char oneKey[] = "abc";
AES_KEY key; 

AES_set_encrypt_key(oneKey,128,&key);
AES_set_decrypt_key(oneKey,128,&key);

//--------------------


string straa("hello world\n");
memcpy((char*)inbuffer,straa.c_str(),13);


printf("%s",inbuffer);
//this prints out fine

AES_encrypt(inbuffer,encryptedbuffer,&key);
//printf("%s",encryptedbuffer);
//this is expected to pring out rubbish, so is commented

AES_decrypt(encryptedbuffer,outbuffer,&key);
printf("%s",outbuffer);
//this is not pringint "hello world"

getchar();

}

I am aware of the fact that once placed in the new buffers, "encryptedbuffer" and "outbuffer", they are not null terminated "\0" , but even so, by printing out the raw data, i'm only getting rubbish after the decryption, At the end of the decryption, i'm assuming the \0 should also be decrypted and therefore the printf should print corectly.

Anyone knows how to make the decyption work?

Also any idea how to print the buffers using C++ libraries, maybe cout, and not printf?

Answer

Mark Wilkins picture Mark Wilkins · Jan 30, 2014

I notice a couple of possible issues:

  • The call to AES_set_decrypt_key uses the same key as the previous call thus overwriting the key value. To make both calls up front like that, it would be necessary to use a separate key instance. Otherwise wait to call AES_set_decrypt_key until after the encryption is done.
  • The key buffer passed to AES_set_encrypt_key needs to be 16 bytes long for the bit depth of 128. As it is, it will read 16 bytes, but the contents of those are undefined.