erandi
erandi

Reputation: 317

PHP openssl_public_encrypt “key parameter is not a valid key”

I have my public key in a file named , publickey.key and the content of that file is this,

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtixUGzGpLXgZ7AV1HfmIHV/FEF+fww77FekRc2oLhUOd4HitwCPo76fjtdsQBEt8w9HZ3CXVphaAU2BA6MEZJ3ShVMsdAXb2ZA1C+lu7k1GV9M/BhucTg35HujSK647Sc5MwVLwFsN80dAnGsZF8gwb2TNUzXHwzbAb30T01zuqf8RCM75OwKZFYqzu7FOVrtk/w9mh92MOXG0l7WSqNIctu8Kxka/tEJJIA5nqMGNMocjwprXy66NS7FFy1GY+NnxfFLtODqq0tllc50UCDsnqSvNmj2wcnAcsCzNOoxPPgp7t8S+sQvOzgc5W3CDjIsYEiGD+vzSVNkGiRou577wIDAQAB

/////// And in my .php file i am following below steps to encrypt my string using this public key

$fp=fopen ("publickey.key","r");
    $publicKey=fread($fp,8192);
    fclose($fp);
$encrypted = '';
$secret='what i want to encrypt';

    if (!openssl_public_encrypt($secret, $encrypted, $publicKey)) 
    {   
        die('Failed to encrypt data');
    }

but i am getting this error.

Warning: openssl_public_encrypt() [function.openssl-public-encrypt]: key parameter is not a valid public key in......

Is there some thing that i am doing wrong in my code? Help Please!

Upvotes: 2

Views: 6819

Answers (1)

neubert
neubert

Reputation: 16782

You probably need to add -----BEGIN RSA PUBLIC KEY----- and -----END RSA PUBLIC KEY----- before and after the key blob. And you might need to use chunk_split, too, because OpenSSL is pretty picky.

Really, though, I'd recommend using phpseclib, a pure PHP RSA implementation. It has much more versatile key handling, among other things.

Upvotes: 2

Related Questions