0

I am getting the following error when the function below runs on Qt Creator

/home/zero/build-EncryptionTask2-Desktop_Qt_5_7_0_GCC_64bit-Debug/EncryptionTask2 crashed.

I think it comes from converting to/from QByteArray data type

QByteArray encryotionProgress(QByteArray d_input)
{
//QByteArray d_output;
params->key = key;
params->iv  = iv;
/* Indicate that we want to encrypt */
   params->encrypt = 1;
/* Set the cipher type you want for encryption-decryption */
  params->cipher_type = EVP_aes_256_cbc();

 /* Encrypt the given file */
   unsigned char *enc_out;

   AES_set_encrypt_key( params->key, 256, &enc_key);
   AES_encrypt((unsigned char*)(d_input.data()), enc_out, &enc_key);
   QByteArray d_output((char*)enc_out);//convert back to qbyte array

  return d_output;
 }
MSalters
  • 173,980
  • 10
  • 155
  • 350
Hamdy Fouad
  • 31
  • 1
  • 9
  • Does `AES_encrypt` produce a null terminated string? If not how does `QByteArray` know the lenghth of the buffer? – drescherjm Mar 22 '18 at 12:53
  • Does AES_encrypt allocate memory for its output ? if it does, you should free it before returning from encryotionProgress to avoid memory leak, if it does not, you should allocate memory for output, before passing pointer to AES_encrypt – Andrew Kashpur Mar 22 '18 at 12:57
  • Is `params` defined? Add condition `if(!params) return;`, its a good practice. Did you use debug to look for possible place where error occured? In most of the cases it a segmentation fault due improper memory management. – Sumit Jha Mar 22 '18 at 12:58
  • 2
    @SumitJha: No, it's not goot practice. The code here is a snippet (unfortunately) but it's likely that `params!=nullptr` is a class invariant. In fact, `return` is downright wrong here. The return type isn't `void`. – MSalters Mar 22 '18 at 13:01
  • Can you provide debugger messages ... – Mohammad Kanan Mar 22 '18 at 13:55

1 Answers1

0

Memory must be allocated to enc_out before passing to function AES_encrypt.

First, get the size of of output buffer:

const int n = sizeof(unsigned char) * ((d_input.length() + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;

Then allocate memory to enc_out using either of the following ways:

C++ style dynamic memory allocation:

unsigned char* enc_out = new unsigned char[n];

C style dynamic memory allocation:

unsigned char* enc_out = (unsigned char *) malloc (n);

Note: Do not forget to free or delete[] memory allocated to enc_out after using it.

Stack memory allocation:

unsigned char  enc_out[n];

I hope it helps.

Sumit Jha
  • 1,601
  • 11
  • 18