我对这个函数有问题
$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: 第14行上的''Users''User''Desktop''examplep''htdocs''chiaveP.php
我该如何解决这个问题?
从您的评论中,我不确定尝试回显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.
*/
您在openssl_pkey_get_private()
上一定得到了一个错误,因为它显然返回了一个布尔值false。来自文档:
成功时返回正密钥资源标识符,出错时返回FALSE。
当方法在错误时返回false时,最好进行检查,因为这会使代码更容易调试。