我的这个功能有问题
$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为 资源,布尔值 第14行的C:\ Users \ User \ Desktop \ xampp \ htdocs \ chiaveP.php
我该如何解决这个问题?
答案 0 :(得分: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.
*/
答案 1 :(得分:0)
你必须在openssl_pkey_get_private()
上收到错误,因为它明显返回一个布尔值false。来自文档:
成功时返回正键资源标识符,错误时返回FALSE。
当方法在出错时返回false时,最好对其进行检查,因为它会使代码更容易调试。