From 44f34c60fe1f1dde859655bbda86221b6cec4811 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Fri, 20 May 2022 12:41:06 +0200 Subject: Truncate ciphertext buffer to actual size during file encryption The ciphertext for AES CTR is exactly as large as the plaintext (not necessarily a multiple of the blocksize!). By truncating the ciphertext, we do not send bytes that will be decrypted to gibberish. As a side node, we probably do not need to initialize the ciphertext buffer larger than the plaintext size at all, but the OpenSSL docs are a bit vague about that. --- lib/events/encryptedfile.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index 9cc3a0c8..140dca7f 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -67,6 +67,7 @@ std::pair EncryptedFile::encryptFile(const QByteArray QByteArray cipherText(plainText.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); + cipherText.resize(length); EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); EVP_CIPHER_CTX_free(ctx); -- cgit v1.2.3 From 59f2b60835752fc87e75f456145d21cc5f77a433 Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Fri, 20 May 2022 20:33:12 +0200 Subject: Apply suggestions from code review Co-authored-by: Alexey Rusakov --- lib/events/encryptedfile.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index 140dca7f..33ebb514 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -64,10 +64,10 @@ std::pair EncryptedFile::encryptFile(const QByteArray int length; auto* ctx = EVP_CIPHER_CTX_new(); - QByteArray cipherText(plainText.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); + const auto blockSize = EVP_CIPHER_CTX_block_size(ctx); + QByteArray cipherText(plainText.size() + blockSize - 1, '\0'); EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); - cipherText.resize(length); EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); EVP_CIPHER_CTX_free(ctx); -- cgit v1.2.3