I’m new here so please excuse if I’m doing something wrong.
I attempt to make an array with encrypted strings, I’m using the EVP API for the encryption. This works fine, but wHen I try to use the encrypt function in a foor loop the console gives me nothing.
Here is my encrypt function:
char *encrypt(char *key, char *iv, char * source){
//char *target;
int in_len, out_len;
EVP_CIPHER_CTX ctx;
in_len=strlen((const char *)source);
unsigned char *target = (unsigned char *) malloc(in_len);
//printf("This is the text before ciphering: %s\n",source);
//printf("The length of the string is: %d\n",in_len);
//starting the encryption process
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx,EVP_aes_128_cbc(),NULL,(unsigned char*) key,(unsigned char*)iv);
EVP_EncryptUpdate(&ctx,target,&out_len,(unsigned char*)source,in_len);
EVP_EncryptFinal_ex(&ctx,target,&out_len);
target[out_len] = '\0';
//EVP_CIPHER_CTX_cleanup(&ctx);
return ((char *)target);
}
and in main the loop:
int main(){
char source[17]="Shahababamamaaaa";
char key[17]="ahardtobreakkey1";
char iv[17] = "veryinterestingv";
int rows = 1280;
int cols = (3*800)/16;
char *encrypted=encrypt(key, iv, source);
printf("encrypted: %s\n", encrypted);
char *encrypted2;
encrypted2=encrypt(key, iv, encrypted);
printf("encrypted2: %s\n", encrypted2);
char *mx[rows];
char *in, *temp;
in = (char *) malloc ( cols * sizeof(char) );
temp =(char *) malloc ( strlen(encrypted) );
int i, j;
for (i=0; i<5; i++){
strcpy(in,encrypted);
for(j=0;j<3;j++){
printf("in: %s\n", in);
strcpy(temp, encrypted2);
printf("temp: %s\n", temp);
memset(encrypted2,0x00, strlen(encrypted));
encrypted2=encrypt(key, iv,temp);
printf("encrypted2 nach j=%d : %s\n",j, encrypted2);
mx[i]=in;
}
}
printf("Stele 0 Inhalt %s\n",mx[0]);
printf("Laenge von 1 %d\n", strlen(mx[0]));
//system ("PAUSE");
free(in);
return 0;
}
What am I missing? Is it imposible to use encrypt2 again?
Thank you very much.
As you said, the main problem is in your encrypt() function, but also how you call it. You are using malloc() to allocate memory inside your function, and never freeing it, which is a memory leak (and malloc is a no-no in c++ anyway). You are also not running the cleanup function for your ctx. And your encrypt_final is overwriting the first part of your output buffer. So, here’s a cleaned up encrypt(), and a matching decrypt():
And to decrypt:
Pulling it all together (in a loop, to prove your concept):