Mac环境nginx – php 使用openssl_pkey_new返回false的问题

php openssl_pkey_new用于生成一个新的私钥,有缺省配置参数:

$res = openssl_pkey_new(array(
	'private_key_bits' => 512,
)); 

while($message = openssl_error_string()) {
	echo $message.'<br />'.PHP_EOL;
}

如果返回false,说明创建失败,查看报错信息:

error:0E06D06C:configuration file routines:NCONF_get_string:no value
error:02001002:system library:fopen:No such file or directory
error:2006D080:BIO routines:BIO_new_file:no such file
error:0E064002:configuration file routines:CONF_load:system lib

配置文件位置不正确,通过phpinfo()查看openssl信息,默认配置路径是

/usr/local/libressl-2.2/etc/ssl/openssl.cnf

但笔者实际Mac环境中并不存在,真正路径是:

/etc/ssl/openssl.cnf

所以,需要正确填入配置即可:

$res = openssl_pkey_new(array(
	'private_key_bits' => 512,
	'config' => '/etc/ssl/openssl.cnf'
)); 

openssl_pkey_export返回null,同样道理,手动加上文件配置:

openssl_pkey_export($res, $private_key, null, array(
	'private_key_bits' => 512,
	'config' => '/etc/ssl/openssl.cnf'
));

完整例子:

$config = array(
	'private_key_bits' => 512,
	'config' => '/etc/ssl/openssl.cnf'
);

//创建公钥和私钥
$res=openssl_pkey_new($config);
 
//提取私钥
openssl_pkey_export($res, $private_key, null, $config );

//生成公钥
$public_key=openssl_pkey_get_details($res);
$public_key=$public_key["key"];

$data = 'test';

openssl_public_encrypt($data, $encrypted, $public_key);
$encrypted = base64_encode($encrypted);  
echo "公钥加密数据:".$encrypted."\n";

openssl_private_decrypt(base64_decode($encrypted), $decrypted, $private_key);  
echo "私钥解密数据:".$decrypted."\n";

参考资料

https://blog.csdn.net/liuxl57805678/article/details/115527586

http://www.04007.cn/article/259.html