Функция шифрования показана ниже. Для шифрования используется EVP_aes_256_cbc(), а ключ доступа генерируется из PKCS5_PBKDF2_HMAC с использованием SHA1.
Код: Выделить всё
const int Cipher::cIterations = 1000;
const int Cipher::cPassSizeBytes = 48;
const int Cipher::cOk = 1;
int Cipher::Encrypt(const string &plainText,
const string &passPhrase,
string &cipherText)
{
const int cKeySizeBytes = 32;
const int cSaltSizeBytes = 32;
const int cIvSizeBytes = 32;
try
{
string key(cKeySizeBytes, 0);
string salt(cSaltSizeBytes, 0);
string iv(cIvSizeBytes, 0);
string password(cPassSizeBytes, 0);
string encryptedStr(cipherText.size(), 0);
int actual_size = 0;
int final_size;
createRandString(salt);
createRandString(iv);
rfc2898DeriveBytes(passPhrase, salt, cIterations, key);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
if(cOk != EVP_EncryptInit_ex(ctx,
EVP_aes_256_cbc(),
NULL,
reinterpret_cast(&key[0]),
reinterpret_cast(&iv[0])))
{
handleErrors();
}
if(cOk != EVP_EncryptUpdate(ctx,
reinterpret_cast(&encryptedStr[0]),
&actual_size,
reinterpret_cast(&plainText[0]),
plainText.size()))
{
handleErrors();
}
if(cOk != EVP_EncryptFinal_ex(ctx,
reinterpret_cast(&encryptedStr[actual_size]),
&final_size))
{
handleErrors();
}
actual_size += final_size;
encryptedStr.resize(actual_size);
cipherText = salt + iv + encryptedStr;
EVP_CIPHER_CTX_cleanup(ctx);
}
catch (std::runtime_error &ex)
{
throw ex;
}
catch (std::exception &ex)
{
std::cerr
Подробнее здесь: [url]https://stackoverflow.com/questions/78408726/openssl-encryption-c-evp-decryptfinal-ex-detects-different-padding-to-applie[/url]