Hey guys,

I was using the low level aes APIs and now have switched to EVP ones. My
string encryption and decryption always work fine. But when it comes to
files, I am getting malloc errors: malloc: *** error for object : incorrect
checksum for freed object - object was probably modified after being freed.

Here is my code for encryption ( decryption is very similar). I am trying
to call this in a loop whenever I have a file to encrypt 32 bytes of data
each time. Is this teh correct way to do it?
Please advice.

unsigned char* encryptBlockAES(unsigned char *plainText, int dataLength,
int *outLength,const unsigned char* keyData, int pageNo)
{

    unsigned char key[AES_BLOCK_SIZE*2], iv[AES_BLOCK_SIZE*2];
    EVP_CIPHER_CTX enCtx;
    int enLength = 0;
    unsigned char* encryptedString;
    int outLen;
    int tempLen;

    enLength = dataLength + (AES_BLOCK_SIZE);
    memset(iv, pageNo, AES_BLOCK_SIZE*2); //Hard coded for now. Will become
a parameter soon
    memset(key, 0, AES_BLOCK_SIZE*2);

    unsigned char* tempKey = generateHash((unsigned char*)keyData,
AES_BLOCK_SIZE*2);
    if (tempKey == NULL)
    {
        fprintf(stderr, "Unable to generate key \n");
        exit(-1);
    }
    memmove(key,tempKey, AES_BLOCK_SIZE*2);

    // alloc encrypt_string
    encryptedString = (unsigned char*)calloc(enLength, sizeof(unsigned
char));
    if (encryptedString == NULL)
    {
        fprintf(stderr, "Unable to allocate memory for encrypt_string\n");
        exit(-1);
    }

    EVP_CIPHER_CTX_init(&enCtx);
    EVP_EncryptInit_ex(&enCtx, EVP_aes_256_cbc(), NULL, key, iv);

    EVP_EncryptUpdate(&enCtx, encryptedString, &outLen, plainText,
enLength);
    EVP_EncryptFinal_ex(&enCtx, encryptedString + outLen, &tempLen);
    *outLength = outLen + tempLen;
    EVP_CIPHER_CTX_cleanup(&enCtx);
    return encryptedString;
}

Thanks,
Tarani

Reply via email to