PHP · 05/14/2019 2

错误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;
}