错误openssl_sign(): supplied key param cannot be coerced into a private key

错误openssl_sign(): supplied key param cannot be coerced into a private key

原因:RSA 的秘钥一般都有固定换行格式

私钥:

$str=’私钥(改成一行)’;

$str = chunk_split($str, 64, "\n");
$key = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
$signature = '';
if (openssl_sign($data, $signature, $key, OPENSSL_ALGO_MD5)) {
    echo base64_encode($signature);
}

公钥:

$data='内容';
$str='公钥(改成一行)';
$str = chunk_split($str, 64, "\n");
$key = "-----BEGIN PUBLIC KEY-----\n$str-----END PUBLIC KEY-----\n";
$signature = "";
if (openssl_verify(base64_decode($data), $signature, $key, OPENSSL_ALGO_MD5) == 1) {
    echo $signature;
}

openssl(SHA1WithRSA) 签名 验签

//签名:
public function wjSign($data){
	$key = openssl_pkey_get_private(file_get_contents($this->privateKeyPathWJ));
	openssl_sign($data, $sign, $key, OPENSSL_ALGO_SHA1);
	$sign = base64_encode($sign);
	return $sign;
}
//验签:
public function wjVerify($data, $sign){
	$sign = base64_decode($sign);
	$key = openssl_pkey_get_public(file_get_contents($this->publicKeyPathWJ));
	$result = openssl_verify($data, $sign, $key, OPENSSL_ALGO_SHA1) === 1;//1成功 0失败 -1错误
	return $result;
}

2 thoughts on “错误openssl_sign(): supplied key param cannot be coerced into a private key

  1. $pk = openssl_pkey_get_private($this->pkey);
    openssl_sign($md5.’key=’.$this->m_key,$sign,$pk,OPENSSL_ALGO_SHA256);
    openssl_free_key($pk);
    $signature = base64_encode($sign);
    return $signature;

    以上是代码

发表评论

电子邮件地址不会被公开。