EDIT: I found out that the keys aren't the problem like I said in the comments. I can use them without any issues to encrypt and decrypt data on OpenSSL.
But I need to decrypt a string on OpenSSL that was previously encrypted via Crypto++ and that's not working.
I'll post additional details later.
Hi, I have encrypted a string using an RSA public key generated with Crypto++ and now I'm trying (still unsuccessful) to decrypt it via PHP and OpenSSL.
That is what I'm doing:
- The private key which is NOT base64 or hex encoded is stored in a file called "rsa-private.key"
- The encrypted message is stored in "message.txt" (hex encoded)
STEP 1: Load the private key via: $key = file_get_contents("rsa-private.key");
STEP 2: Convert the key into PEM format using the following function:
<?php
function pkcs8_to_pem($der) {
static $BEGIN_MARKER = "-----BEGIN PRIVATE KEY-----";
static $END_MARKER = "-----END PRIVATE KEY-----";
$value = base64_encode($der);
$pem = $BEGIN_MARKER . "\n";
$pem .= chunk_split($value, 64, "\n");
$pem .= $END_MARKER . "\n";
return $pem;
}
$PEMprivatekey = pkcs8_to_pem($key);
?>
( stackoverflow.com/questions/1357569/ )
STEP 3: Prepare the key for further use by OpenSSL: (without any problems)
<?php
$privateKey = openssl_get_privatekey($PEMprivatekey);
if (!$privateKey) {
echo "Cannot get public key";
}
?>
STEP 4: Get the message and decode the message using the following function:
<?php
function hex_to_str($hex){
for ($i=0; $i < strlen($hex)-1; $i+=2) {
$string .= chr(hexdec($hex[$i].$hex[$i+1])); }
return $string;
}
$message = file_get_contents("message.txt");`
$encryptedstring = hex_to_str($message);
?>
STEP 5: Decrypt the string: (does not work)
<?php
openssl_private_decrypt($encryptedstring, $decrypteddata, $privateKey);
if (!$decrypteddata) {
echo "........"; } else { echo $decrypteddata; }
?>
$decrypteddata is always empty.
I can't figure out why it's not working. Anyone noticed something I'm doing wrong?