php使用openssl進行數位簽章驗證

來源:互聯網
上載者:User

標籤:安全   bsp   get   creat   接收   string   date   簽名   ase   

 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,表示簽名驗證通過

 

php使用openssl進行數位簽章驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.