php使用openssl进行数字签名验证

时间:2021-11-29 08:03:23
 1 <?php
2 /**
3 * Created by PhpStorm.
4 * User: hanks
5 * Date: 6/2/2017
6 * Time: 6:03 PM
7 */
8 /*
9 【数字签名】
10 使用完全加密的数据进行传输的好处是更加安全,但是计算更加复杂,需要传输的数据也更多,
11 更常用的方式只是对要传输的数据做一个数字签名,在接收端对接收到的数据进行一个签名运算,
12 只要客户端计算的签名和接受的的签名一样就可以认为收到的数据没有被篡改过。
13
14 计算签名使用openssl提供的openssl_sign(),签名验证使用openssl_verify()
15 这两个函数的函数签名为:
16
17 bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] )
18 int openssl_verify ( string $data , string $signature , mixed $pub_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] )
19 通过参数比较容易理解函数的使用,sign函数第一个函数是一个字符串,所以对数组,
20 对象等签名需要使用json_encode或者base64_encode等函数编码一下;
21 第二个参数是&$signature就是函数会把对数据$data的签名保存在$signature变量。
22
23 注意返回值,第一个函数是bool值,第二个是int,1表示签名验证通过, 0表示签名不正确,-1表示发生错误。*/
24
25 $publicKey = file_get_contents('./php-public.key');
26 $privateKey = file_get_contents('./php-private.key');
27
28 $data = [
29 'orderId' => 100002,
30 'pay_time' => '2015-09-02 10:10:10',
31 'extra'=>'额外的数据'
32 ];
33 $signature = '';
34 openssl_sign(json_encode($data), $signature, $privateKey);
35 echo 'sign is: ' . base64_encode($signature);
36
37 //这里做实验,手动的篡改下orderId的键值
38 //$data = [
39 // 'orderId' => 100003,
40 // 'pay_time' => '2015-09-02 10:10:10',
41 // 'extra'=>'额外的数据'
42 //];
43
44 $verify = openssl_verify(json_encode($data), $signature, $publicKey);
45
46 echo "\nverify result: $verify";//返回的将是0,即签名不正确,返回1,表示签名验证通过