Search code examples
phpc++encryption-symmetric

Can I decrypt data in C++ encrypted via PHP?


I'm using mcrypt_encrypt and base64_encode to encrypt data in php. I've tried decrypting the data in C++, but to no avail. I have C++ Rijndael logic that I've used for years, as well as base64_decode logic. The latter decodes strings encoded by php's base64_encode perfectly. I'm using CBC with both the php and C++. I've experimented with different block sizes and so forth but to no avail. Any advice greatly appreciated.

This is my test logic:

PHP

$key = "qwertyuiopasdfghjklzxcvbnmqwerty";  
$iv = "12345678901234561234567890123456";  
$text = "this is the text to encrypt";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
echo base64_encode($crypttext)."<br/>";

C++

char* base64encode = ".. output from php...";  
unsigned char binaryData[256];  
int binaryNumBytes;  
char result[256];  
base64_decode(reinterpret_cast<unsigned char*>(base64encode), strlen(base64encode),       binaryData, &binaryNumBytes, false);  
Encryption::Rijndael rijndael;  
char* key = "qwertyuiopasdfghjklzxcvbnmqwerty";  
char* iv = "12345678901234561234567890123456";  
rijndael.Init(Encryption::Rijndael::CBC, reinterpret_cast<const char*>(key), 32, 32,    reinterpret_cast<const char*>(iv));  
rijndael.Decrypt(reinterpret_cast<const char*>(binaryData), reinterpret_cast<char*>(result), 32);  
cout << result << endl; 

EDIT: If I use ECB mode I can get this to work. There is some issue then with CBC between the 2.


Solution

  • Using ECB mode was the way to go.