环境: win10/php7.0
用phpinfo()查看openssl的配置时,发现一个Bug
win10的环境下,openssl.cnf文件默认目录居然是在c:/usr/local/ssl/openssl.cnf
因此在该环境下使用openssl时,需要指定openssl.cnf文件路径
public function createNewRsaKey()
{
$config = [
'digest_alg' => 'sha512',
'private_key_bits' => 4096,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
'config' => 'E:\php\php7.0.9nts\extras\ssl\openssl.cnf', //openssl.cnf文件路径,windows下openssl.cnf默认位置为c://usr//local//ssl 应该是个bug,需要指定相应文件路径
];
// 创建密钥对
$res = openssl_pkey_new($config);
//错误信息反馈
while ($msg = openssl_error_string()) {
return $msg;
}
// 从$res中提取私钥,这里也需要用$config
openssl_pkey_export($res, $privKey, null, $config);
// 从$res中提取公钥
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey['key'];
return [
'public' => $pubKey,
'private' => $privKey
];
}
我在win10上用的phpstudy提供php环境,使用过程中遇到一个bug,每次请求了一次密钥对后,再次请求就会报错:
"error:0E06D06C:configuration file routines:NCONF_get_string:no value"
这个问题非常神奇,每次重启Nginx服务器就能重新获取密钥对。openssl.cnf文件只是被读取过,没有被修改过,这个问题的根源我没想清楚,也许是phpstudy的bug,还需要后续的进一步实验。之后我会把代码布置到ubuntu上再看看会不会有这个Bug,排查一下nginx的问题。
加密解密方法/**
* 公钥加密数据
* @param string $data
* @param $publicKey
* @return string
* @throws Exception
*/
public function rsaPubEncryption($publicKey, string $data = '')
{
if (!is_string($data)) {
throw new Exception('Invalid parameter type');
}
return openssl_public_encrypt($data, $encrypted, $publicKey) ? base64_encode($encrypted) : '';
}
/**
* 私钥解密
* @param $encryption
* @param $privKey
* @return mixed
*/
public function rsaPrivDecryption($privKey, $encryption)
{
openssl_private_decrypt(base64_decode($encryption), $decrypted, $privKey);
return $decrypted;
}
/**
* 私钥加密
* @param $privKey
* @param string $data
* @return string
* @throws Exception
*/
public function rsaPrivEncryption($privKey, string $data = '')
{
if (!is_string($data)) {
throw new Exception('Invalid parameter type');
}
return openssl_public_encrypt($data, $encrypted, $privKey) ? base64_encode($encrypted) : '';
}
/**
* 公钥解密
* @param $publicKey
* @param $encryption
* @return mixed
*/
public function rsaPubDecryption($publicKey, $encryption)
{
openssl_private_decrypt(base64_decode($encryption), $decrypted, $publicKey);
return $decrypted;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)