我有一个函数可以加密某些字符串,以便在C ++中传输到我的客户端应用程序。我在PHP中用来生成加密字符串的函数:
<?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;
}
?>
但是,当我尝试使用下面显示的函数在C ++中解密此结果时,它没有正确返回字符串(缺少最后部分)。
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
请注意,对于某些字符串,C ++中的解密可以正常工作。但是,对于其他字符串,输出如上所述,仅部分解密并丢失最后部分。也许这是某种填充问题,因为一些字符串被正确解密?那么,我的代码出了什么问题?
上面代码中使用的字符串只是一个示例字符串,用于澄清问题。