I have a function which encrypts certain strings for transfer to my client application in C++. The function I use in PHP to generate the encrypted string:
<?php
echo EncryptForTransfer("This is a test"); //returns: l4/r5AUDTrPTlIfVyG0=DJKlty0VgWPSNsM2XbzkOZ79ivQA2eBWTd18FKVfgslM6UmP
function EncryptForTransfer($EncryptMe) {
$Key = random_string(32);
$IV = random_string(16);
return openssl_encrypt($EncryptMe, "AES-256-CFB", (string)$Key, false, $IV).$IV.$Key;
}
?>
However, when I try to decrypt this result in C++ with the functions shown underneath, it is not returning me the string correctly (missing last parts).
int Decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) {
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cfb(), NULL, key, iv)) {
handleErrors();
}
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
handleErrors();
}
plaintext_len = len;
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) {
handleErrors();
}
plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
string DecryptFromTransfer(string DecryptMe) {
long long DecryptFromTransferLength = DecryptMe.length();
string TransferKey = DecryptMe.substr(DecryptFromTransferLength - 32, 32);
string TransferIV = DecryptMe.substr(DecryptFromTransferLength - 32 - 16, 16);
string DecryptMeOriginal = DecryptMe.substr(0, DecryptFromTransferLength - 32 - 16);
return DecryptThis(DecryptMeOriginal, TransferKey, TransferIV);
}
cout << DecryptFromTransfer("l4/r5AUDTrPTlIfVyG0=DJKlty0VgWPSNsM2XbzkOZ79ivQA2eBWTd18FKVfgslM6UmP"); //returns: This is
Please note that for some strings the decryption in C++ works correctly. However, for other strings the output is as stated above, only partially decrypted and missing the last parts. Maybe it is some kind of padding issue since some strings are decrypted correctly? So, what is wrong with my code?
The used string in the code above is just an example string to clarify the issue.