在window系统,PHP开启了openssl扩展,打开phpinfo显示openssl已经成功加载,但是在使用openssl相关函数的时候,比如openssl_pkey_new 这个函数的时候,一直都是返回false。实际方法如下:
function createKey($privKey = null) { //配置参数 $config = array( 'private_key_bits' => 2048, ); if ($privKey != null) { $res = openssl_pkey_get_private($privKey); } else { $res = openssl_pkey_new($config); openssl_pkey_export($res, $privKey, null, $config); } $array = openssl_pkey_get_details($res); $pubKey = $array['key']; openssl_pkey_free($res); return array('pubKey' => $pubKey, 'privKey' => $privKey); }
在Linux系统下,该方法能够生成一对公私钥,但是在window环境中却返回为空。
解决方法有两种
方法一:
$config = array(
'private_key_bits' => 2048,
'config' => ../openssl.cnf
);
在$config中加入‘config’参数,其中引入openssl.cnf文件的路径,使用这种方法可以暂时有效的生成公私钥,但是不好的地方就是,每个需要用到openssl.cnf的函数,都需要进入这个文件路径。
方法二:完美解决
打开PHPinfo,查看openssl扩展,发现
发现openssl default config 的路径是c:/usr/local.ssl/openss.cnf,window系统并没有这个路径,打开linux发现,这个路径下确实有一个openssl.cnf的文件,这就很好说明了linux有效而window无效的问题了,于是我在window的C盘下面创建这个路径,把openssl.cnf文件放到这个路径下,再次运行程序,完美解决问题。