ECDSA-php 加密解密

 1 <?php  
 2 
 3 class Ecdsa
 4 {
 5     private $alg;
 6 
 7     public function __construct() {
 8         $this->alg = OPENSSL_ALGO_SHA256;
 9     }
10 
11     /**
12      * 加密
13      * @param privateKeyString  私钥
14      * @param message  请求数据(数组)
15      */
16     public function php_encry($privateKeyString = '', $message = []) {
17         $privateKey = openssl_get_privatekey($privateKeyString);
18 
19         $message = json_encode($message, JSON_PRETTY_PRINT);
20 
21         $signature = null;
22         if (openssl_sign($message, $signature, $privateKey, $this->alg)) {
23             $signature = base64_encode($signature);
24             return $signature;
25         } else {
26             return openssl_error_string();
27         }
28     }
29 
30     /**
31      * 验签
32      * @param publicKeyString  公钥
33      * @param message  请求json串
34      * @param signature  base64加密后的字符串
35      */
36     public function php_decry($publicKeyString = '', $message = [], $signature = '') {
37         $publicKey = openssl_get_publickey($publicKeyString);
38 
39         $message = json_encode($message, JSON_PRETTY_PRINT);
40 
41         $return = [
42             'code' => 0,
43             'message' => 'error'
44         ];
45 
46         //验证签名
47         $success = openssl_verify($message, base64_decode($signature), $publicKey, $this->alg);
48         if ($success === -1) {
49             $return['message'] = openssl_error_string();
50             return $return;
51         } elseif ($success === 1) {
52             $return['code'] = 1;
53             $return['message'] = 'success';
54             return $return;
55         } else {
56             $return['message'] = openssl_error_string();
57             return $return;
58         }
59     }
60 }
61 
62 //var_dump(openssl_get_md_methods());die;
63 
64 $ec = new Ecdsa();
65 
66 $private_key = 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQglCkOi90fqXJ3u1J0l1RwP0FTfv08
67     LYzSwj+B0vAJq3ehRANCAARu/5R3QWhJ6EBK/UTL7Zg/IP4ixFFZAcMMNnRdwKSopGhwxhksw93F
68     ZeH5f7RUSL8m5rNLrKyIm/AhpOFd2LJe';
69 
70 $privateKeyString =
71 "-----BEGIN EC PARAMETERS-----
72 BgUrgQQACg==
73 -----END EC PARAMETERS-----
74 -----BEGIN EC PRIVATE KEY-----
75 ".$private_key."
76 -----END EC PRIVATE KEY-----";
77 
78 $public_key = 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEbv+Ud0FoSehASv1Ey+2YPyD+IsRRWQHDDDZ0XcCkqKRocMYZLMPdxWXh+X+0VEi/JuazS6ysiJvwIaThXdiyXg==';
79 $publicKeyString =
80 "-----BEGIN PUBLIC KEY-----
81 ".$public_key."
82 -----END PUBLIC KEY-----";
83 
84 $message = '欧阳草帽';
85 
86 $sign = $ec->php_encry($privateKeyString, $message);
87 echo $sign.'<br>';
88 $res = $ec->php_decry($publicKeyString, $message, $sign);
89 echo $res['message'];
View Code

 

posted @ 2020-01-07 12:37  心静,路远  阅读(1076)  评论(0编辑  收藏  举报