if (data.isEmpty())
return false;
// Generate the password
unsigned char random_byte;
RAND_bytes(&random_byte, 1);
int passwordSize = 9; // +(random_byte % 3) * 3; // Random size of 9, 12, or 15
std::vector<unsigned char> password(passwordSize);
RAND_bytes(password.data(), passwordSize);
// Generate a random salt
RAND_bytes(&random_byte, 1);
int saltSize = 9; // +(random_byte % 3) * 3; // Random size of 9, 12, or 15
std::vector<unsigned char> salt(saltSize);
RAND_bytes(salt.data(), saltSize);
// Encode the salt as base64
BIO* bio = BIO_push(BIO_new(BIO_f_base64()), BIO_new(BIO_s_mem()));
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio, salt.data(), saltSize);
BIO_flush(bio);
BUF_MEM* bptr;
BIO_get_mem_ptr(bio, &bptr);
std::vector<unsigned char> b64Salt(bptr->length);
memcpy(b64Salt.data(), bptr->data, bptr->length);
OPENSSL_cleanse(bptr->data, bptr->length);
OPENSSL_cleanse(bptr, sizeof(*bptr));
BIO_free_all(bio);
// SHA256 the salt and password
int b64SaltSize = b64Salt.size();
unsigned char keyHash[SHA256_DIGEST_LENGTH];
unsigned char ivHash[SHA256_DIGEST_LENGTH];
SHA256(password.data(), passwordSize, keyHash);
SHA256(b64Salt.data(), b64SaltSize, ivHash);
std::vector<unsigned char> hashedKey(16);
std::vector<unsigned char> hashedIv(16);
bio = BIO_push(BIO_new(BIO_f_base64()), BIO_new(BIO_s_mem()));
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
if (BIO_write(bio, keyHash, SHA256_DIGEST_LENGTH) != SHA256_DIGEST_LENGTH ||
BIO_flush(bio) != 1)
{
BIO_free_all(bio);
return false;
}
BIO_get_mem_ptr(bio, &bptr);
std::memcpy(hashedKey.data(), bptr->data, 16);
BIO_reset(bio);
if (BIO_write(bio, ivHash, SHA256_DIGEST_LENGTH) != SHA256_DIGEST_LENGTH ||
BIO_flush(bio) != 1)
{
BIO_free_all(bio);
return false;
}
BIO_get_mem_ptr(bio, &bptr);
std::memcpy(hashedIv.data(), bptr->data, 16);
BIO_free_all(bio);
OPENSSL_cleanse(keyHash, sizeof(keyHash));
OPENSSL_cleanse(ivHash, sizeof(ivHash));
std::vector<unsigned char> cipherBuf(data.size() + EVP_MAX_BLOCK_LENGTH);
const EVP_CIPHER* cipherType = EVP_aes_128_cbc();
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx)
return false;
if (EVP_EncryptInit_ex(ctx, cipherType, NULL, hashedKey.data(), hashedIv.data()) != 1)
{
OPENSSL_cleanse(data.data(), data.size());
data.clear();
EVP_CIPHER_CTX_free(ctx);
return false;
}
OPENSSL_cleanse(hashedKey.data(), hashedKey.size());
OPENSSL_cleanse(hashedIv.data(), hashedIv.size());
int outLength1 = 0;
if (EVP_EncryptUpdate(ctx, cipherBuf.data(), &outLength1,
reinterpret_cast<unsigned char*>(data.data()), data.size()) != 1)
{
OPENSSL_cleanse(data.data(), data.size());
data.clear();
EVP_CIPHER_CTX_free(ctx);
return false;
}
int outLength2 = 0;
if (EVP_EncryptFinal_ex(ctx, cipherBuf.data() + outLength1, &outLength2) != 1)
{
OPENSSL_cleanse(data.data(), data.size());
data.clear();
EVP_CIPHER_CTX_free(ctx);
return false;
}
EVP_CIPHER_CTX_free(ctx);
cipherBuf.resize(outLength1 + outLength2);
OPENSSL_cleanse(data.data(), data.size());
data.clear();
// Generate random string to prepend
unsigned char randomByte;
RAND_bytes(&randomByte, 1);
int prependStrSize = 4; // 4 + (randomByte % 7); // Random size between 4 and 10
std::vector<unsigned char> prependStr(prependStrSize);
RAND_bytes(prependStr.data(), prependStrSize);
data.append(prependStr);
data.append(password);
data.append(salt);
data.append(cipherBuf);
VM_S_END // C898
return true;
}
You do not need to convert keyHash and ivHash to Base64 for the purpose of deriving your AES key and IV. Base64 encoding is typically used to represent binary data in an ASCII string format, which is useful for transmitting data over text-based protocols or for storing it in text files. However, when dealing with cryptographic keys and IVs— which are binary data—you can and should work with them in their raw binary form to maintain their integrity and security.
Simplifying Your Code
Here's how you can modify your code to eliminate the unnecessary Base64 encoding:
Directly Use SHA256 Hash Outputs:
Instead of encoding the SHA256 hashes in Base64 and then truncating them, you can directly use the first 16 bytes of the hash for your AES-128 key and IV.
Separate IV Generation:
It's generally recommended to use a random IV for each encryption operation rather than deriving it from a hash. This ensures that the same plaintext encrypted multiple times will yield different ciphertexts, enhancing security.
Updated Code Example
Below is a revised version of your weakEncrypt2 function reflecting these changes:
cpp
#include <openssl/sha.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <vector>
#include <cstring>
// ...
inline bool weakEncrypt2(QByteArray& data)
{
VM_S_START // C898
if (data.isEmpty())
return false;
// Generate a random password
int passwordSize = 12; // Fixed size for simplicity
std::vector<unsigned char> password(passwordSize);
RAND_bytes(password.data(), passwordSize);
// Generate a random salt
int saltSize = 12; // Fixed size for simplicity
std::vector<unsigned char> salt(saltSize);
RAND_bytes(salt.data(), saltSize);
// SHA256 the password and salt without Base64 encoding
unsigned char keyHash[SHA256_DIGEST_LENGTH];
unsigned char ivHash[SHA256_DIGEST_LENGTH];
SHA256(password.data(), passwordSize, keyHash);
SHA256(salt.data(), saltSize, ivHash);
// Derive the AES key and IV by taking the first 16 bytes of the hash
unsigned char hashedKey[16];
unsigned char hashedIv[16];
std::memcpy(hashedKey, keyHash, 16);
std::memcpy(hashedIv, ivHash, 16);
// Clean up sensitive data
OPENSSL_cleanse(keyHash, sizeof(keyHash));
OPENSSL_cleanse(ivHash, sizeof(ivHash));
// Initialize encryption
std::vector<unsigned char> cipherBuf(data.size() + EVP_MAX_BLOCK_LENGTH);
const EVP_CIPHER* cipherType = EVP_aes_128_cbc();
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx)
return false;
if (EVP_EncryptInit_ex(ctx, cipherType, NULL, hashedKey, hashedIv) != 1)
{
OPENSSL_cleanse(data.data(), data.size());
data.clear();
EVP_CIPHER_CTX_free(ctx);
return false;
}
// Clean up key and IV after use
OPENSSL_cleanse(hashedKey, sizeof(hashedKey));
OPENSSL_cleanse(hashedIv, sizeof(hashedIv));
int outLength1 = 0;
if (EVP_EncryptUpdate(ctx, cipherBuf.data(), &outLength1,
reinterpret_cast<unsigned char*>(data.data()), data.size()) != 1)
{
OPENSSL_cleanse(data.data(), data.size());
data.clear();
EVP_CIPHER_CTX_free(ctx);
return false;
}
int outLength2 = 0;
if (EVP_EncryptFinal_ex(ctx, cipherBuf.data() + outLength1, &outLength2) != 1)
{
OPENSSL_cleanse(data.data(), data.size());
data.clear();
EVP_CIPHER_CTX_free(ctx);
return false;
}
EVP_CIPHER_CTX_free(ctx);
cipherBuf.resize(outLength1 + outLength2);
OPENSSL_cleanse(data.data(), data.size());
data.clear();
// Generate a random IV to prepend (recommended approach)
std::vector<unsigned char> prependIv(EVP_CIPHER_iv_length(cipherType));
RAND_bytes(prependIv.data(), prependIv.size());
// It's better to store the IV alongside the ciphertext
data.append(reinterpret_cast<char*>(prependIv.data()), prependIv.size());
data.append(reinterpret_cast<char*>(password.data()), password.size());
data.append(reinterpret_cast<char*>(salt.data()), salt.size());
data.append(reinterpret_cast<char*>(cipherBuf.data()), cipherBuf.size());
VM_S_END // C898
return true;
}
Key Changes and Recommendations
Removed Base64 Encoding:
Previous Approach: Salt was Base64-encoded before hashing, and the hash was also Base64-encoded before truncating to derive the key and IV.
Updated Approach: Directly hash the raw salt and password without Base64 encoding. Use the first 16 bytes of each SHA256 hash as the AES key and IV.
Fixed Sizes for Password and Salt:
For simplicity and predictability, consider using fixed sizes for the password and salt (e.g., 12 bytes). Variable sizes can complicate key derivation and data parsing.
Proper IV Handling:
Recommended: Use a randomly generated IV for each encryption operation and store it alongside the ciphertext. This enhances security by ensuring that the same plaintext encrypted multiple times produces different ciphertexts.
Updated Approach: Generate a random IV (prependIv) and prepend it to the encrypted data. This IV can be extracted and used during decryption.
Security Improvements:
Key Derivation: While using SHA256 and truncating works, it's more secure to use a Key Derivation Function (KDF) like PBKDF2, scrypt, or Argon2. These functions are designed to be computationally intensive, making brute-force attacks more difficult.
Encryption Method: Ensure that AES-128-CBC is suitable for your use case. Depending on your requirements, other modes like AES-GCM might offer authenticated encryption, providing both confidentiality and integrity.
Sensitive Data Handling:
Use OPENSSL_cleanse to erase sensitive data from memory after use to prevent leakage.
Ensure that all sensitive variables (keys, IVs, passwords) are properly handled and not exposed or logged.
Error Handling:
Ensure comprehensive error handling, cleaning up resources and sensitive data appropriately in all failure cases.
Additional Considerations
Authenticated Encryption: Consider using an authenticated encryption mode (e.g., AES-GCM) to provide integrity checks alongside confidentiality.
Secure Password Storage: If passwords are user-generated or stored, ensure they are handled securely, possibly leveraging a secure password storage mechanism or integrating with a secure authentication library.
Code Maintainability and Clarity: Simplifying the key and IV derivation process not only enhances security but also improves code readability and maintainability.
Conclusion
Base64 encoding of keyHash and ivHash is unnecessary for deriving AES keys and IVs. Removing these steps simplifies your code and avoids potential sources of errors or inefficiencies. However, ensure that you follow best practices for key derivation and IV handling to maintain the security of your encryption mechanism.