PHP openssl_public_encrypt "key parameter is not a valid key"

It occured to me why it wasn't working, so I am here to answer my own question. Now that I think about it, it ties into what @sarnold originally said: the + signs are gone (and they got replaced by spaces)

it turns out that because i was getting the key via HTTP POST, it formatted the URL (and thus the key) turning all the + signs into spaces. That threw off the key and caused this conundrum.

Thanks for the help. :)


First, I would recommend using phpseclib, a pure PHP RSA implementation. It's a ton more portable and easier to use and all that jazz. Example:

<?php
$key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtixUGzGpLXgZ7AV1HfmIHV/FEF+fww77FekRc2oLhUOd4HitwCPo76fjtdsQBEt8w9HZ3CXVphaAU2BA6MEZJ3ShVMsdAXb2ZA1C+lu7k1GV9M/BhucTg35HujSK647Sc5MwVLwFsN80dAnGsZF8gwb2TNUzXHwzbAb30T01zuqf8RCM75OwKZFYqzu7FOVrtk/w9mh92MOXG0l7WSqNIctu8Kxka/tEJJIA5nqMGNMocjwprXy66NS7FFy1GY+NnxfFLtODqq0tllc50UCDsnqSvNmj2wcnAcsCzNOoxPPgp7t8S+sQvOzgc5W3CDjIsYEiGD+vzSVNkGiRou577wIDAQAB';

$rsa = new Crypt_RSA();
$rsa->loadKey($key);
$rsa->setPublicKey($key);

echo $rsa->getPublicKey();

If you insist on using the openssl extension... try this:

"-----BEGIN PUBLIC KEY-----\r\n" . chunk_split($whatever) . "\r\n-----END PUBLIC KEY-----"

Simply use str_replace(' ', '+', $string)

Worked for me!