Php – Get the key parameter is not a valid public key error in openssl_public_encrypt()

encryptionopensslPHPphp-opensslpublic-key-encryption

$publicKey = "../ssh/public/pub";
$plaintext = "String to encrypt";

$pubKey = openssl_pkey_get_public($publicKey);

openssl_public_encrypt($plaintext, $encrypted, $pubKey);

echo $encrypted;   //encrypted string

above code generating following error

openssl_public_encrypt() [http://php.net/function.openssl-public-encrypt]: key parameter is not a valid public key [APP/controllers/supportservice_controller.php, line 144]

I created the keys with openssl using:

generate a 1024 bit rsa private key, ask for a passphrase to encrypt it and save to file
openssl genrsa -des3 -out /path/to/privatekey 1024

generate the public key for the private key and save to file

openssl rsa -in /path/to/privatekey -pubout -out /path/to/publickey

Best Answer

In my case,I Splited the public key into mutiple lines,solved the problem.

PHP Version 7.1.17

    $publicKey = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($publicKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";

    $str = "str to be encrypted";

    $opensslPublicEncrypt = openssl_public_encrypt($str, $encrypted, $publicKey);
Related Topic