PHP 验签
Sign 验签数据准备:
- 公钥(Public key)
- Sign签名(一般是base64加密过的)
- Data参数(参数列表,Sign对应的参数值)
php的openssl扩展里已经封装好了验签的方法openssl_verify。
如果在Windows下的php.ini需要开启Openssl模块:
extension=php_openssl.dll
这里再解释一下openssl_verify函数:
int openssl_verify ( string $data , string $signature , mixed $pub_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )
openssl_verify() 函数来验证sign签名是否正确,是通过指定的data数据和公钥相关的pub_key_id来实现的。
从支付接口获取到的公钥Public key,如下:
—–BEGIN PUBLIC KEY—–
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxJUb3d2QTkW67SILT33Y
GqmP8HmXqtXpM5DPKFibkMs2f6tk+52qe3aOb4/bryqG754o5s1Yg/9o9duwE3VL
If9tuFVQ6TSrN2cacjDNXsW3aIkk6HdBvytrj/XJePQIXmjZZjPGqbDdItmJxUI+
HXYDxiaZIe4kuVRA8FbKr6iZ5uW9bfO5N2GY+IncPFFZivDa2Xq8kuOwxyZXi+cX
4W9LnsYrkq3jZ5/9RGNGzXJMs+GkFUKFqaHWhqW5xAwsKQcD8xiLuwAHt6wGIfy1
R2yQQQwetK02i44MvKRCEX8tlUYvCvr0T38B3kX2hHgmIxP3Cpv5jbJts+mMD7cG
iQIDAQAB
—–END PUBLIC KEY—–
注 意这个是2048位的公钥应该是9行或者10行,不能为1行,不然PHP的openssl_pkey_get_public无法读 取,pub_key_id的结果为false,我就在这个上吃了大亏。如果没有—–BEGIN PUBLIC KEY—– 和 —–END PUBLIC KEY—– 可以自己加上,最后保存到一个rsa_public_key.pem文件中。像这样:
<?php $public_key = file_get_contents(dirname(__FILE__).’/rsa_public_key.pem’); $pkeyid = openssl_pkey_get_public($public_key); $data = ‘abc’; $sign = ‘WkMaSsx9Fbj9/YyjoM1X0SLYvaFbsz9VmMaxc42fXxamEEIj5AfqQLrygEZRq0gkLNT4heIwOiSWEAWbfD4imaERKk07ANXEtZJ9jPJvyvg70IVvaYMKAr7bX0dJXmYw4aHnkcWR1kz27Drr6fxPmchB9WCsRmi4VfhVoF1+HRFOp28nIVReGRcbwbW1/bcMisXbitirz9Wq396vY88GUSgbgNdhFXX/kzjRBTjnG+CIhXq4HPdOWovqtPhQoxmK55+V+vxNZk9OPPHHaN3vVswk062NOs2/05yNVObL+PWeg/m43buXYalmkrwEhemdGfjIdNEoSO2D4gikvm43cg==’; $sign = base64_decode($sign); if ($pkeyid) { $verify = openssl_verify($data, $sign, $pkeyid, OPENSSL_ALGO_MD5); openssl_free_key($pkeyid); } var_dump($verify); ?>