我想加密和解密C++庫和PHP服務器之間使用OPENSSL庫在它們中的通信。我想使用Blowfish CBC算法,但似乎C++代碼和PHP代碼的結果不同。 C++代碼就是從這裏採取:OPENSSL Blowfish CBC加密不同於PHP到C++
這是PHP代碼:
<?php
function strtohex($x)
{
$s='';
foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
return($s);
}
$encryptedMessage = openssl_encrypt("input", "BF-CBC", "123456", 0, "initvect");
echo $encryptedMessage;
echo "\n";
echo strtohex($encryptedMessage);
的PHP輸出是這樣的:
x9jDa2WMwvQ=
78396A446132574D7776513D
這是C++代碼:
bool do_encrypt(const char *in, unsigned char *out, int *outlen, unsigned char *key, unsigned char *iv)
{
int buflen, tmplen;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_bf_cbc(), nullptr, key, iv);
if (!EVP_EncryptUpdate(&ctx, out, &buflen, (unsigned char*)in, strlen(in)))
{
return false;
}
if (!EVP_EncryptFinal_ex(&ctx, out + buflen, &tmplen))
{
return false;
}
buflen += tmplen;
*outlen = buflen;
EVP_CIPHER_CTX_cleanup(&ctx);
return true;
}
unsigned char output[2048] = { 0 };
int outLen;
auto result = do_encrypt("input", output, &outLen, (unsigned char*)"123456", (unsigned char*)"initvect");
BIGNUM *outputStr = BN_new();
BN_bin2bn(output, outLen, outputStr);
cout << base64_encode(output, outLen) << "\n";
cout << BN_bn2hex(outputStr) << "\n";
C++的輸出是這樣的:
EfRhhWqGmSQ=
11F461856A869924
有人可以幫助我瞭解我做錯了什麼嗎?任何幫助將非常感激。
謝謝!
編輯1: 我設法解決後JWW的答案C++代碼,效果不錯。我錯過了EVP_CIPHER_CTX_set_key_length但是,我無法讓PHP代碼返回相同的結果,最終我們決定轉向AES,現在它完美地工作。謝謝!
你可能想對OpenSSL的維基快速看一下[EVP對稱加密和解密(http://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption)。事實上,您應該使用經過身份驗證的加密,因爲它提供了*機密性和真實性。請參閱OpenSSL wiki上的[EVP Authenticated Encryption and Decryption](http://wiki.openssl.org/index.php/EVP_Authenticated_Encryption_and_Decryption)。 – jww
感謝您的建議。我會研究它。但是現在,將PHP端點更改爲使用不同的加密並不容易。 – saw66
河豚不再被認爲是安全的,即使它的發明者現在使用AES。 – zaph