openssl_verify,警告:openssl_verify():提供的密钥参数不能被强制转换为公钥

时间:2015-12-07 18:25:10

标签: php openssl signature verify

此文件出现此错误:

<?php
// $data and $signature are assumed to contain the data and the signature

$signature = null;
$toSign = "C:/Users/User/Desktop/xampp/htdocs/docum.docx";

$fp = fopen("key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

openssl_sign($toSign, $signature, $pkeyid);

openssl_free_key($pkeyid);
echo($signature);
// fetch public key from certificate and ready it
$fp = fopen("C:/Users/User/Desktop/xampp/htdocs/pubkey.der", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($toSign, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

如何修复此错误?`... 我用文档的私钥计算了签名,现在我想测试它。 起初我创建了两个php文件,第一个签署文件,第二个发生了我签名。我只是不知道如何从第一份文件中取出签名。他决定把它们全部放在一起试试......我该如何解决?

1 个答案:

答案 0 :(得分:0)

  1. 绝对确定您的公钥文件短于8192字节?如果您只是想将文件读入变量使用file_get_contents(),那就更简单了。
  2. openssl_get_publickey($cert)返回了什么?
  3. 根据您得到的错误,OpenSSL看起来像PEM格式的密钥,因此您需要转换它。
  4. 尝试:

    function der2pem($der_data) {
       $pem = chunk_split(base64_encode($der_data), 64, "\n");
       $pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
       return $pem;
    }
    
    $cert = der2pem(file_get_contents('C:/Users/User/Desktop/xampp/htdocs/pubkey.der'));
    
    if( ! $pubkeyid = openssl_get_publickey($cert) ) {
        throw new \Exception(openssl_error_string());
    }