'OpenSSL EVP AES CTR 256 encryption performance for thousands of time at one time

I am using the OpenSSL EVP AES 256 to perform the encryption. The general code flow would be shown as below:

Encrypt() {
 ctx = EVP_CIPHER_CTX_new();
 EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, key, iv);

 EVP_EncryptUpdate(ctx, ciphertext, &out_len, plaintext, plaintext_len);
 EVP_EncryptFinal_ex(ctx, ciphertext + out_len, &out_len)
}

But, you can see each time we need to create the context, init, and then perform the encryption. In my user case, I need to encrypt thousands of strings at one time. It will take several seconds which is not acceptable.

And then I changed the code as following: I want to init once and then call encryption thousands of times as I need. But, for the second time Encrypt() will return the unexpected strings.

EncryptInit() {
 ctx = EVP_CIPHER_CTX_new();
 EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, key, iv);
}

Encrypt() {
 EVP_EncryptUpdate(ctx, ciphertext, &out_len, plaintext, plaintext_len);
 EVP_EncryptFinal_ex(ctx, ciphertext + out_len, &out_len)
}

Can someone tell me what's wrong with this? And How to improve the performance for my user case?

Thanks a lot!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source