Reputation: 1087
I am trying to use the evp encryption and decryption libraries for encryption/ decryption of message data over tcp sockets. I first create the cipher context using EVP_CIPHER_CTX_new()
, then init it using EVP_EncryptInit_ex(newctx, EVP_aes_256_gcm(), NULL, crypkey, iv)
and then use the EncryptUpdate
calls before sending data over socket.
Everything works fine if every EncryptUpdate
call is followed by a socket send
call. But if I try to encrypt and store something for sending later then I always get corrupted encrypted data.
Since I am totally new to this, I can't help but wonder if this is by design or am I missing something really simple here.
On further search, best i could find was that gcm
mode maintains a counter on both encryption and decryption side as mentioned in the comment. Does this imply that Encryptupdate
is state based at the very least?
Example code below. When I send enpkt2
, the server receiver will reject it because it is expecting the packet that was encrypted first. Else the context on server and client sides would go out of sync. Am I wrong with the above understanding?
EVP_CIPHER_CTX *enctx;
enctx = EVP_CIPHER_CTX_new();
if (1 != EVP_EncryptInit_ex(enctx, EVP_aes_256_gcm(), NULL, crypkey, iv))
printf("ENCRYPT init failed\n");
unsigned char *pkt1, *enpkt1, *pkt2, *enpkt2;
int ciplen1, ciplen2;
if (1 != EVP_EncryptUpdate(enctx, enpkt1, &ciplen1, pkt1, pktlen1))
printf("encrypt error\n");
if (1 != EVP_EncryptUpdate(enctx, enpkt2, &ciplen2, pkt2, pktlen2))
printf("encrypt error\n");
send(socket, enpkt2, ciplen2);
Upvotes: 1
Views: 167