简体   繁体   中英

openssl_pkey_export and “cannot get key from parameter 1”

I need to use openssl within my php project, so I created a test php page using openssl. However, I keep getting these errors and I am not sure why. openssl is enabled.

Warning: openssl_pkey_export() [function.openssl-pkey-export]: cannot get key from parameter 1 in C:\\wamp\\www\\opensslsample\\index.php on line 18

Warning: openssl_pkey_get_details() expects parameter 1 to be resource, boolean given in C:\\wamp\\www\\opensslsample\\index.php on line 21

<?php
 //echo phpinfo();

   $privateKey = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));

openssl_pkey_export($privateKey, $privkey,"123");

$pubkey=openssl_pkey_get_details($privateKey);
$pubkey=$pubkey["key"];
?>

This may help if you are on windows:

  1. Click on the START button
  2. Click on CONTROL PANEL
  3. Click on SYSTEM AND SECURITY
  4. Click on SYSTEM
  5. Click on ADVANCED SYSTEM SETTINGS
  6. Click on ENVIRONMENT VARIABLES
  7. Under "System Variables" click on "NEW"
  8. Enter the "Variable name" OPENSSL_CONF
  9. Enter the "Variable value". My is - C:\\wamp\\bin\\apache\\Apache2.2.17\\conf\\openssl.cnf
  10. Click "OK" and close all the windows and RESTART your computer.

The OPENSSL should be correctly working.

Check openssl_error_string . My guess is that your openssl.cnf file is missing or something.

Alternatively, you could use phpseclib, a pure PHP RSA implementation , to generate keys. eg.

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();

extract($rsa->createKey());

echo "$privatekey<br />$publickey";
?>

The PHP needs to find your openssl.cnf. The best way to achieve this is to add the directory location of it in the PATH environment variable.

I extract from phpseclib to fix it in jose-jwt lib and it worked, you need this several changes:

<?php

$config = array();
$config['config'] = dirname(__FILE__) . '/openssl.cnf';

$privateKey = openssl_pkey_new(array(
  'private_key_bits' => 1024,
  'private_key_type' => OPENSSL_KEYTYPE_RSA,
) + $config);

openssl_pkey_export($privateKey, $privkey, "123", $config);

And this minimalist config file:

# minimalist openssl.cnf file for use with phpseclib

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

[ v3_ca ]

Called openssl.cnf . With all this it should work well.

You can workaround by using ParagonIE\\EasyRSA\\KeyPair. Take a look at https://github.com/paragonie/EasyRSA .

Warning: openssl_pkey_export(): cannot get key from parameter 1 in C:\\xampp\\htdocs\\info.php on line 57

Warning: openssl_pkey_get_details() expects parameter 1 to be resource, bool given in C:\\xampp\\htdocs\\info.php on line 60

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM