【问题标题】:Private Key with PHP and "openssl_pkey_get_details() expects parameter 1 to be resource"带有 PHP 的私钥和“openssl_pkey_get_details() 期望参数 1 是资源”
【发布时间】:2016-03-10 12:02:32
【问题描述】:

这个功能有问题

$priv_key = openssl_pkey_get_private(file_get_contents("server.pem"));

$keyData = openssl_pkey_get_details($priv_key);

$keyData['key'] = str_replace('-----BEGIN PRIVATE KEY-----', '', $keyData['key']);
$keyData['key']= trim(str_replace('-----END PRIVATE KEY-----','',$keyData['key']));

echo $keyData['key'];

它应该返回私钥,但它给了我这个错误

警告:openssl_pkey_get_details() 期望参数 1 为 资源,布尔值 C:\Users\User\Desktop\xampp\htdocs\chiaveP.php 在第 14 行

我该如何解决这个问题?

【问题讨论】:

标签: php openssl key private


【解决方案1】:

我不确定您的评论是否尝试回显 server.pem 文件的内容失败,或者您的意思是整个脚本。希望下面的代码将有助于确定问题所在!

<?php

    $debug=true;
    $cert='/full/path/to/server.pem';/* this should be outside the document root */
    $keytype='PRIVATE KEY';/* this is here because in testing I have an `RSA PRIVATE KEY` */


    if( realpath( $cert ) ){
        /* The file exists at the path given: read the contents */

        $priv_key = openssl_pkey_get_private( file_get_contents( realpath( $cert ) ) );

        if( $priv_key ) {

            $keyData = openssl_pkey_get_details( $priv_key );

            $keyData['key'] = str_replace( '-----BEGIN '.$keytype.'-----', '', $keyData['key'] );
            $keyData['key'] = trim( str_replace( '-----END '.$keytype.'-----','',$keyData['key'] ) );   

            echo $keyData['key'];   
        } else {
            echo $debug ? 'failed to read private key' : 'error #1';
        }
    } else {
        echo $debug ? 'unable to find ' . $cert : 'error #2';   
    }

?>

作为一种可能的选择,正如您所说,.pem 文件与 php 脚本位于同一目录中,也许可以尝试:

$data=file_get_contents(realpath(__DIR__.DIRECTORY_SEPARATOR.'server.pem'));
echo $debug ? $data : '';
$priv_key = openssl_pkey_get_private( $data );

/*
    I tried using the path ( `c:/wwwroot/certificates/server.pem` ) as the parameter to the
    `openssl_pkey_get_private` rather than actually reading the contents into a string 
    but that failed. The method above however worked for me when the cert was in the same dir.
*/

【讨论】:

  • 此时是不是私钥文件不好?我在终端上使用命令 genrsa -des3 -out server.pem 1024 openssl 创建了
  • 在尝试生成证书时,我花了很长时间才弄清各个方面的正确性——我还不能 100% 确定它们是否完美。我发现的一个棘手的问题是正确设置配置文件(openssl.cnf),并且可以通过 php 脚本(在 Windows 上通过设置正确的环境变量和路径)定位并且可供 apache 访问
  • 它返回私钥并在浏览器中打印...非常感谢...谢谢您uuuuu
【解决方案2】:

openssl_pkey_get_private() 上一定有一个错误,因为它显然返回了一个布尔值 false。来自文档:

成功时返回正的密钥资源标识符,错误时返回 FALSE。

当方法在错误时返回 false 时进行检查是个好主意,因为它使您的代码更易于调试。

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多