错误 0x2006D002:BIO 例程:BIO_new_file:在 Windows 上使用 PHP 的系统库


Error 0x2006D002:BIO routines:BIO_new_file:system lib with PHP on Windows

我在尝试通过简单方式加载私钥时收到以下错误。这是我的代码。

public function loadPrivateKey($fileName, $password = null){
        if(!is_file($fileName))
            throw new SignException('Private key not found', SignException::KEY_NOT_FOUND);
        $fileContent = file_get_contents($fileName);
        if(!is_null($password))
            $this->prvKey = openssl_get_privatekey($fileContent, $password);
        else
            $this->prvKey = openssl_get_privatekey($fileContent);
        if(!empty(openssl_error_string()))
            throw new SignException('OpenSSL Error: '.openssl_error_string());
        if(!is_resource($this->prvKey))
            throw new SignException('Private key is not resourse', SignException::EXTERNAL_ERROR);
    }

openssl_error_string()返回error:2006D002:BIO routines:BIO_new_file:system lib .

我在php.ini中启用了OpenSSL,extension=php_openssl.dll

可能是什么问题?我该如何解决?

谢谢!

函数 openssl_get_privatekey()openssl_pkey_get_private() 的别名。此函数接受两个参数;第一个是 URI 格式的文件名,或者是 PEM 格式的私钥的内容。第二个是密码短语。

您收到的错误表示尝试读取文件时出错;通常,有问题的文件包含在错误消息中,因此您可能只在此处包含部分错误。由于您没有使用 OpenSSL 读取文件,因此最有可能的罪魁祸首是 OpenSSL 配置文件;需要告诉系统在哪里寻找它。

  • 右键单击我的电脑并进入属性
  • 在高级选项卡上,单击环境变量按钮
  • 在"系统变量"下创建新条目
  • 变量名称应为"OPENSSL_CONF">
  • 变量值应该是文件的完整路径
  • 重新启动计算机

环境变量也可以从 PHP 代码中设置,尽管需要将其添加到所有代码中,因此可能不是可取的。此外,如前所述,您可以直接从函数调用中打开密钥文件;以下是我建议尝试的内容:

<?php
public function loadPrivateKey($fileName, $password = "") {
    // I just used the value from my system here
    putenv("OPENSSL_CONF=C:''OpenSSL''bin''openssl.cfg");
    if (!is_readable($fileName)) {
        throw new SignException("Private key not found or not readable", SignException::KEY_NOT_FOUND);
    }
    $fileName = "file://$fileName";
    $this->prvKey = openssl_get_privatekey($fileName, $password);
    if (!empty(openssl_error_string())) {
        throw new SignException("OpenSSL error: " . openssl_error_string());
    }
    if (!is_resource($this->prvKey)) {
        throw new SignException("Private key is not resource", SignException::EXTERNAL_ERROR);
    }
}