在 C++ 中发出加密字符串并在 PHP 中解密

Issue encrypting string in C++ and decrypting in PHP

我在用 C++ 加密我的字符串然后在 PHP 中解密时遇到问题。在 C++ 方面,我认为一切都很好。下面是我的 C++ 端代码。

unsigned char inbuffer[1024];

unsigned char outbuffer[1024];

unsigned char oneKey[] = "abc";
AES_KEY key;

AES_set_encrypt_key(oneKey, 128, &key);

string straa("hello world\n");
memcpy((char*)inbuffer, straa.c_str(), 13);

AES_encrypt(inbuffer, encryptedbuffer, &key);

LPCSTR pszSource = (LPCSTR)encryptedbuffer;
DWORD nDestinationSize;
if (CryptBinaryToString(reinterpret_cast<const BYTE*> (pszSource), strlen(pszSource), CRYPT_STRING_BASE64, nullptr, &nDestinationSize))
{
    LPTSTR pszDestination = static_cast<LPTSTR> (HeapAlloc(GetProcessHeap(), HEAP_NO_SERIALIZE, nDestinationSize * sizeof(TCHAR)));
    if (pszDestination)
    {
        if (CryptBinaryToString(reinterpret_cast<const BYTE*> (pszSource), strlen(pszSource), CRYPT_STRING_BASE64, pszDestination, &nDestinationSize))
        {

            printf("OUT: %s", pszDestination); // Base64 encoded output of encrypted string


        }

    }
}

这是我的 PHP 代码:

$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
$out = openssl_decrypt(base64_decode("G6g0f/K7EzAw8fxn9BTFzw=="), 'AES-256-CBC', "abc", OPENSSL_RAW_DATA, $iv);

echo $out;

PHP 代码没有输出。

C++ 代码将输出以下内容:

OUT: G6g0f/K7EzAw8fxn9BTFzw==

CBC模式,即PHP代码中使用的模式,确实需要一个iv,并且它必须与用于加密的模式相同,而且加密和解密的模式必须相同。对于 CBC 模式,您需要提供块大小的 iv(AES 为 16 字节)。加密密钥的大小也应该正确。

C++代码中没有显式设置iv,mode和padding使用默认值,最好排除;直接指定所有参数。每次加密的 iv 应该是随机的。

您可以考虑 RNCryptor,它是多语言和多平台的,可以处理所有细节。