Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

$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

like image 822
poojitha Avatar asked Sep 17 '13 06:09

poojitha


3 Answers

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);
like image 61
严水发 Avatar answered Nov 18 '22 06:11

严水发


In PHP 7.x and new versions of phpseclib (a pure PHP RSA implementation) and using composer to install phpseclib, you can do this:

    # Install the phpseclib from console
    composer require phpseclib/phpseclib:~2.0
    // In your php script:

    use phpseclib\Crypt\RSA;

    $rsa = new RSA();
    $rsa->loadKey($publicKey); # $publicKey is an string like "QEFAAOCAQ8AMIIBCgKCAQEAoHcbG....."
    $plaintext = '...';
    $ciphertext = $rsa->encrypt($plaintext);

    var_dump($ciphertext);

    #to decrypt:
    $rsa->loadKey('...'); // private key
    echo $rsa->decrypt($ciphertext);```



like image 4
manuelpgs Avatar answered Nov 18 '22 05:11

manuelpgs


Like this you can add your key and encrypt the text

  $data = json_decode(file_get_contents('php://input'), true);
  $enctext = $data['enctext'];

  $pubkey = '-----BEGIN PUBLIC KEY-----
             PUBLIC  KEY PLACED HERE
             -----END PUBLIC KEY-----';

  openssl_public_encrypt($enctext, $crypted, $pubkey);
  $data['enctext'] =  $enctext;
  $data['Encryption_text'] = base64_encode($crypted);
  echo json_encode($data);
  exit;

Or instead of this you can also call a .cert file of public key

  $fp=fopen("publickey.crt","r"); 
  $pub_key_string=fread($fp,8192); 
  fclose($fp); 
  $key_resource = openssl_get_publickey($pub_key_string); 

  openssl_public_encrypt($enctext, $crypted, $key_resource );
  $data['enctext'] =  $enctext;
  $data['Encryption_text'] = base64_encode($crypted);
  echo json_encode($data);
  exit;
like image 2
Kashyap Patel Avatar answered Nov 18 '22 07:11

Kashyap Patel