栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

php配置使用openssl

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

php配置使用openssl

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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/268740.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号