1

When I'm encrypting a variable where I put some text in it, it's working, but if I'm using a variable where I'm assigning to the $output this:

$data1 = new DOMDocument("1.0", "utf-8");
//creating the xml document
...
//after creating the document
$output = $data1->saveXML();

where $data1 is an xml object. After that I'm using a public certificate to extract the public key, for encrypting the string $output:

$pub_key = openssl_pkey_get_public(file_get_contents('./certificate.cer'));
$keyData = openssl_pkey_get_details($pub_key);
$key = $keyData['key'];

After I have the public key in the variable $key, I want to encrypt the $output with the public key $key, and I'm using the following code to handle possible error:

$crypted='';
if (($blnResult = openssl_public_encrypt($output, $crypted, $key)) === false) {
    throw new \Exception("error: openssl_public_encrypt() failed!");
}

echo base64_encode($crypted);

And it gives me the error: openssl_public_encrypt() failed!. Notice that if I'm assigning to $output='foo', it's working, so I don't understand why it isn't working if I'm assigning to $output the data->saveXML();? It is a 270 characters long string. It "should" work.

jww
  • 97,681
  • 90
  • 411
  • 885
B. Victor
  • 94
  • 1
  • 8
  • Possible duplicate of [openssl\_public\_encrypt not working](https://stackoverflow.com/questions/46378455/openssl-public-encrypt-not-working) – matt Sep 23 '17 at 13:22
  • What’s the key size? A 2048 bit key can encrypt up to 245 bytes. – matt Sep 23 '17 at 14:25
  • I guess it's a 2048 bit key. I saw that I can't give more than 117 characters. So what can I do to increase the size? – B. Victor Sep 23 '17 at 14:30
  • Stop using RSA to encrypt directly. `openssl_seal()` is safer. Switching to libsodium and using `sodium_crypto_box_seal()` is even better. – Scott Arciszewski Dec 29 '17 at 05:23

1 Answers1

2

I had the same problem. My problem was that either the public key I used was very short or the data I was trying to encrypt was very long. So, you have 2 options: - You may reduce the amount of data you are trying to encrypt or, - You may use a public key that allows you to encrypt more data (a bigger public key)

Reference: https://en.wikipedia.org/wiki/RSA_(cryptosystem)

hikna
  • 43
  • 1
  • 8
  • This saved me so much time! I also had a similar problem where some requests we were sending to a 3rd party were working while others were failing. After reading this, we requested another key which worked. Thanks! – jkoech Nov 06 '19 at 10:44