我试图通过简单的方式加载我的私人密钥时出现以下错误。 这是我的代码。
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_get_privatekey()
的别名。 这个函数有两个参数。 第一个是URI格式的文件名,或者是PEM格式的私钥的内容。 第二个是密码。
您收到的错误表明尝试读取文件时出错; 通常有问题的文件被包含在错误信息中 ,所以你可能只在这里包含错误的一部分。 由于您没有使用OpenSSL读取文件,最可能的罪魁祸首是OpenSSL配置文件; 系统需要被告知在哪里寻找它。
环境变量也可以从你的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); } }