php配置使用openssl

本文讲述了在Windows环境下PHP7.0使用openssl时,由于默认openssl.cnf路径问题导致的bug,以及如何正确指定路径。作者还分享了RSA密钥对生成、加密解密方法,并计划在Ubuntu上验证问题是否存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php配置使用openssl

环境: 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:phpphp7.0.9ntsextrassslopenssl.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的问题。

加密解密方法

 


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) : '';
}


public function rsaPrivDecryption($privKey, $encryption)
{
    openssl_private_decrypt(base64_decode($encryption), $decrypted, $privKey);
    return $decrypted;
}


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) : '';
}



public function rsaPubDecryption($publicKey, $encryption)
{
    openssl_private_decrypt(base64_decode($encryption), $decrypted, $publicKey);
    return $decrypted;
}

文章转自:php配置使用openssl_PHP-考高分网 (kaotop.com)icon-default.png?t=M1L8http://www.kaotop.com/it/268740.html 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值