標籤:sub publickey ext 手冊 output type 模組 details open
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: hanks 5 * Date: 6/2/2017 6 * Time: 6:03 PM 7 */ 8 //使用php函數產生金鑰組 9 //openssl模組提供了很多openssl相關的函數,參考手冊 產生金鑰組的方法如下:10 $privateKey = openssl_pkey_new([11 ‘private_key_bits‘ => 2048, // private key的大小12 ‘private_key_type‘ => OPENSSL_KEYTYPE_RSA,13 ]);14 15 openssl_pkey_export_to_file($privateKey, ‘php-private.key‘);16 $key = openssl_pkey_get_details($privateKey);17 file_put_contents(‘php-public.key‘, $key[‘key‘]);18 19 openssl_free_key($privateKey); // 釋放資源
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: hanks 5 * Date: 6/8/2017 6 * Time: 12:20 PM 7 */ 8 //使用金鑰組加密資料 9 //使用第一步的php函數產生的公開金鑰對一段明文進行分段(chunk)再分段加密,(實際使用中也可以直接全部文本加密):10 //$plain = ‘this is a 測試的資料‘;11 $plain = [12 0=>[13 ‘0‘=>‘sd‘,14 ‘1‘=>‘使得‘15 ],16 1=>[17 ‘0‘=>‘sd2‘,18 ‘1‘=>‘使得2‘19 ],20 ];21 echo ‘plian text: ‘ . json_encode($plain,true);22 $plain = gzcompress(json_encode($plain,true)); // compress data23 $pubkeyStr = file_get_contents(‘./php-public.key‘);24 $publicKey = openssl_pkey_get_public($pubkeyStr);25 26 $p_key = openssl_pkey_get_details($publicKey);27 $chunkSize = ceil($p_key[‘bits‘] / 8) -11; // 這裡不知道為什麼要-11,後面追加解釋28 29 $output = ‘‘;30 31 while ($plain) {32 $chunk = substr($plain, 0, $chunkSize);33 $plain = substr($plain, $chunkSize);34 35 $encrypted = ‘‘;36 if ( !openssl_public_encrypt($chunk, $encrypted, $publicKey)) {37 die("failed to encrypt data");38 }39 $output .= $encrypted;40 }41 openssl_free_key($publicKey);42 $output = base64_encode($output);43 echo ‘encrypted: ‘ . ($output);44 file_put_contents(‘./enc.data‘, $output);
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: hanks 5 * Date: 6/8/2017 6 * Time: 12:22 PM 7 */ 8 //解密資料 9 //使用私密金鑰對資料進行解密:10 $keyStr = file_get_contents(‘./php-private.key‘);11 if (!$privateKey = openssl_pkey_get_private($keyStr)) {12 die(‘get private key failed‘);13 }14 15 $encrypted = file_get_contents(‘./enc.data‘);16 echo ‘encrypted data: ‘ . $encrypted;17 18 $encrypted = base64_decode($encrypted);19 20 $p_key = openssl_pkey_get_details($privateKey);21 $chunkSize = ceil($p_key[‘bits‘] / 8);22 $output = ‘‘;23 24 while ($encrypted) {25 $chunk = substr($encrypted, 0, $chunkSize);26 $encrypted = substr($encrypted, $chunkSize);27 $decryptd = ‘‘;28 if (!openssl_private_decrypt($chunk, $decryptd, $privateKey)) {29 die(‘failed to decrypt data‘);30 }31 $output .= $decryptd;32 }33 openssl_free_key($privateKey);34 $output = gzuncompress($output);35 echo "\ndecrypted data: ";36 var_dump(json_decode($output,true));
php使用openssl加密資料